Implementation Code for conversion between DP and PX in Android

Source: Internet
Author: User

In the XML layout file, we can set both PX and dp (or DIP ). We usually choose to use DP to ensure the layout of machines with different screen resolutions is consistent. HoweverCodeHow to deal with it? Many control methods only provide the method for setting PX, such as setpadding, and do not provide the method for setting DP. At this time, if you need to set the DP, You need to convert the DP to PX.

The following is an application class that facilitates conversion between PX and DP.

Copy codeThe Code is as follows: Import Android. content. context;

Public class densityutil {

/**
* Convert the cell phone resolution from Dp to PX (pixel)
*/
Public static int dip2px (context, float dpvalue ){
Final float scale = context. getresources (). getdisplaymetrics (). density;
Return (INT) (dpvalue * scale + 0.5f );
}

/**
* Convert pixel to DP based on the resolution of the mobile phone
*/
Public static int px2dip (context, float pxvalue ){
Final float scale = context. getresources (). getdisplaymetrics (). density;
Return (INT) (pxvalue/scale + 0.5f );
}
}

Related Article

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.