Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to use dip (density independent pixel) in code?

Tags:

android

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)
like image 353
ab11 Avatar asked Apr 14 '11 21:04

ab11


People also ask

Can I use dp in CSS?

When writing CSS, use px wherever dp or sp is stated. Dp only needs to be used in developing for Android. When designing for the web, replace dp with px (for pixel). This is answer.

How does dp work Android?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.

Is dp same as px?

Definitions. px or dot is a pixel on the physical screen. dpi are pixels per inch on the physical screen and represent the density of the display. dip or dp are density-indenpendant pixels, i.e. they correspond to more or less pixels depending on the physical density.


1 Answers

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.

like image 85
dontangg Avatar answered Sep 20 '22 20:09

dontangg