Set margins in dp programmatically – Android

Home / Android / Set margins in dp programmatically – Android

Sometimes at runtime, it is required to set margin to a view. But, the problem is getting different size for different screen sizes, i.e. hdpi, xhdpi, xxhdpi, etc.

This could be done easily with the help of screen specific value resources.

Provide screen specific dimension

values/dimen.xml

2dp

values-hdpi/dimen.xml

4dp

values-xhdpi/dimen.xml

6dp

values-xxhdpi/dimen.xml

8dp

Calculate the pixels taken by dp

For setting margins programmatically, we need to convert dp into px. This could be done by calling this method.




public static int getPixelValue(Context context, int dimenId) {
    Resources resources = context.getResources();
    return (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dimenId, 
        resources.getDisplayMetrics()
    );
}

Set LayoutParams to the view

To set margin to the view create LayoutParams instance, and set margin to the view.

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);
int left = getPixelValue(this, getResources().getDimension(R.dimen.margin_top_list_item));
int top = getPixelValue(this, getResources().getDimension(R.dimen.margin_top_list_item));
int right = getPixelValue(this, getResources().getDimension(R.dimen.margin_top_list_item));
int bottom = getPixelValue(this, getResources().getDimension(R.dimen.margin_top_list_item));
layoutParams.setMargins(left, top, right, bottom);
yourView.setLayoutParams(layoutParams);

NOTE: In this example, LinearLayout.LayoutParams is used by assuming that the View yourView is enclosed within LinearLayout. If the view is enclosed within any other Layout, use the <ParentLayout>.LayoutParams, instead.