Method 1:
Resources resources = getResources ();
Float fPx = TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_DIP, 300, resources. getDisplayMetrics ());
// Int iPx = Math. round (fPx );
// Similarly, px to dip:
Float fDip = TypedValue. applyDimension (TypedValue. COMPLEX_UNIT_PX, 300, resources. getDisplayMetrics ());
// Int iDip = Math. round (fDip );
Method 2:
/**
* Convert the cell phone resolution from dp to px (pixel)
*/
Public static int dip2px (Context context, float dpValue)
{
Final float scale = context. getResources (). getDisplayMetrics (). density;
Return (int) (dpValue * scale) + 0.5f );
}
/**
* Convert pixel to dp based on the resolution of the mobile phone
*/
Public static int px2dip (Context context, float pxValue)
{
Final float scale = context. getResources (). getDisplayMetrics (). density;
Return (int) (pxValue/scale) + 0.5f );
}