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

<dimen name="margin_top_list_item">2dp</dimen>

values-hdpi/dimen.xml

<dimen name="margin_top_list_item">4dp</dimen>

values-xhdpi/dimen.xml

<dimen name="margin_top_list_item">6dp</dimen>

values-xxhdpi/dimen.xml

<dimen name="margin_top_list_item">8dp</dimen>

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.

(adsbygoogle = window.adsbygoogle || []).push({});

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.