Px to Dp conversion in Android

I am into a situation where I need to set the width of the TextView programatically to 50 . I need to convert this 50 to dp as I did not find any provision to set the width as dp programatically. Can any one help me how do we convert pixels to dps in Android.


Thanks in Advance.

Upvotes: 0

Views: 291

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82553

Here's a couple of utility methods I wrote ages ago, which seem to come in handy very often:

/**
 * Converts pixel to dip.
 * 
 * @param pixel
 *            that should be converted.
 * @return the converted rounded dip.
 */
private int pixelToDip(int pixel) {
    DisplayMetrics displayMetrics = mContext.getResources()
            .getDisplayMetrics();
    return (int) ((pixel / displayMetrics.density) + 0.5);
}

/**
 * Converts dip to pixel.
 * 
 * @param dip
 *            that should be converted.
 * @return the converted rounded pixel.
 */
private int dipToPixel(int dip) {
    DisplayMetrics displayMetrics = mContext.getResources()
            .getDisplayMetrics();
    return (int) ((dip * displayMetrics.density) + 0.5);
}

You'll either have to run this in a subclass of Context, or have it get a Context from somewhere. I pass in a Context in my Utility class constructor and store it in mContext.

Upvotes: 2

Related Questions