16

How do I specify that an int parameter is in dip? Specifically, how would write the equivalent of:

android:layout_width="50dip" 
android:layout_height="50dip" 

Something like...:

LayoutParams params = new LayoutParams(50, 50)
ab11
  • 19,320
  • 39
  • 109
  • 199

2 Answers2

18

There is a built-in method that will do this too: TypedValue.applyDimension.

// Convert from 50dip to actual pixels
final int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
final int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());

LayoutParams params = new LayoutParams(width, height);

You can use this to convert from sp units to pixels as well.

dontangg
  • 4,696
  • 1
  • 24
  • 36
  • I always thought this was a lack of functionality in Android. It seems it's not lacking, just not very pretty. :D – domenukk Jan 18 '14 at 00:10
17

Use the formula mentioned here http://developer.android.com/guide/practices/screens_support.html#screen-independence for converting default pixel to density independent pixel. OR check this What is the correct way to specify dimensions in DIP from Java code?

Community
  • 1
  • 1
yogsma
  • 9,568
  • 28
  • 92
  • 149