Convert between DP and PX in Android

Source: Internet
Author: User

In the XML layout file, we can either set the PX or set the DP (or DIP). In general, we will choose to use DP, which will ensure that the layout of different screen resolutions on the machine is consistent. But in the code, how to deal with it? Many of the methods in the control provide only a method for setting PX, such as setpadding, and do not provide a way to set the DP. At this point, if you need to set the DP, it is necessary to convert the DP into PX. The following is an application class that facilitates the conversion between PX and DP. Import Android.content.Context; public class Densityutil {/** * turns from DP units to px (pixels) */public static int dip2px (context context, float Dpvalue) based on the resolution of the phone {

Final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Dpvalue * scale + 0.5f);

}/** * from PX (pixel) units to DP * Depending on the resolution of the phone

public static int Px2dip (context context, float Pxvalue) {

Final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue/scale + 0.5f);

}

Convert between DP and PX in Android

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.