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,770
  • 42
  • 120
  • 207

1 Answers1

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,729
  • 1
  • 26
  • 38
  • 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