Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margins of a LinearLayout, programmatically with dp

Tags:

android

Is it possible to set the Margins of a LinearLayout, programmatically but not with pixels, but dp?

like image 262
Eurig Jones Avatar asked Feb 06 '11 14:02

Eurig Jones


People also ask

How do I set margins to recyclerView programmatically?

margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.


1 Answers

You can use DisplayMetrics and determine the screen density. Something like this:

int dpValue = 5; // margin in dips float d = context.getResources().getDisplayMetrics().density; int margin = (int)(dpValue * d); // margin in pixels 

As I remember it's better to use flooring for offsets and rounding for widths.

like image 145
Roman Mazur Avatar answered Oct 14 '22 18:10

Roman Mazur