Conversion between Android DP and PX

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.