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





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.

Set LayoutParams to the view

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

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.

About Krrishnaaaa

Socially known as Navkrishna.. An Android application developer. He likes to create tutorials and post them here or on YouTube or GitHub.. All these activities are shared on Facebook, Twitter, and G+ page.