Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does setWidth(int pixels) use dip or px?

Does setWidth(int pixels) use device independent pixel or physical pixel as unit? For example, does setWidth(100) set the a view's width to 100 dips or 100 pxs?

Thanks.

like image 324
user256239 Avatar asked Mar 09 '10 03:03

user256239


People also ask

What is the difference between PX dip dp and SP?

px - one pixel Corresponds to actual pixels on the screen. Pixel is the smallest controllable element of a picture represented on the screen. sp - Scale-independent Pixels This is like the dp unit. scaled by the user's font size preference.

Is dp the same as PX?

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

How can I use dp instead of PX?

A dp is equal to one physical pixel on a screen with a density of 160. To calculate dp: dp = (width in pixels *... A dp is equal to one physical pixel on a screen with a density of 160.


2 Answers

It uses pixels, but I'm sure you're wondering how to use dips instead. The answer is in TypedValue.applyDimension(). Here's an example of how to convert dips to px in code:

// Converts 14 dip into its equivalent px Resources r = getResources(); int px = Math.round(TypedValue.applyDimension(     TypedValue.COMPLEX_UNIT_DIP, 14,r.getDisplayMetrics())); 
like image 125
Dan Lew Avatar answered Sep 27 '22 22:09

Dan Lew


The correct way to obtain a constant number of DIPs in code is to create a resources XML file containing dp values a bit like:

<?xml version="1.0" encoding="utf-8"?> <resources>     <dimen name="image_width">100dp</dimen>     <dimen name="image_height">75dp</dimen> </resources> 

Then refer to the resource in your code like so:

float width = getResources().getDimension(R.dimen.image_width)); float height = getResources().getDimension(R.dimen.image_height)); 

The float you have returned will be scaled accordingly for the pixel density of the device and so you don't need to keep replicating a conversion method throughout your application.

like image 41
SDJMcHattie Avatar answered Sep 27 '22 23:09

SDJMcHattie