To convert dp to pixel
public static int dp2px(Resources resource, int dp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,resource.getDisplayMetrics()
);
}
To convert pixel to dp.
public static float px2dp(Resources resource, float px) {
return (float)TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PX,
px,
resource.getDisplayMetrics()
);
}
where resource is context.getResources().