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.

  1. Import  Android.content.Context;
  2. Public class densityutil {
  3. /**
  4. * Switch from DP unit to PX (pixel) According to the resolution of the phone
  5.      */   
  6. Public   static int dip2px (context context, float dpvalue) {
  7. Final   Float scale = Context.getresources (). Getdisplaymetrics (). density;
  8. return  (int) (Dpvalue * scale + 0. 5f);
  9. }
  10. /**
  11. * According to the resolution of the phone from PX (pixel) to the unit to become DP
  12.      */   
  13. Public static int Px2dip (context context, float pxvalue) {
  14. Final   Float scale = Context.getresources (). Getdisplaymetrics (). density;
  15. return  (int) (Pxvalue/scale + 0. 5f);
  16. }
  17. }

http://blog.csdn.net/arui319/article/details/6777133

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.