In development, you may need to dynamically set the size of the control
For example, set the width for a gridview:
Linearlayout.layoutparams linearParams2 = (linearlayout.layoutparams) head_gridview.getlayoutparams (); int realwidth = utils.dp2px (context, +), linearparams2.width= (Headadapter.getcount ()) * (realwidth); linearparams2.height=30; Head_gridview.setlayoutparams (LINEARPARAMS2);
At this point we set a fixed number directly to the width, which is treated as a pixel, and the effect is likely to be different from what we want.
At this point we just have to do the DP px correlation conversion, the code is as follows:
/** * DP turns into PX * @param context Context Object * @param dp DP value * @return PX value * */public static int dp2px (context, float DP) { final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (DP * scale + 0.5f); } /**PX to DP * @param context Context Object * @param px Pixel value * @return DP value * */public static int PX2DP (context contexts, float px ) { final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Px/scale + 0.5f); }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Conversion between Android DP and PX