Screen adaptation for Android devices

Source: Internet
Author: User

When we do this, we usually encounter the following resolutions:

Generally, Google engineers have helped us solve the problem. In Android, we have two units: dip and sp. This is different from the general pixel. But according

The Unit after proportional adaptation for different resolutions. SP is also an adaptive unit. Therefore, as long as the two units are used, there is almost no adaptation problem. Using DP and SP, the system

It is automatically converted according to the changes in screen density. Therefore, the control configured in XML does not have the adaptation problem.

However, in some cases, we need to dynamically add controls in the Code. In this case, the control size can only be set through code, and the code device can only set its pixel size.

When this control is set with code, there is a adaption problem. It is particularly large in small resolution and small in large resolution. The following solution is introduced. Below

Is a tool class:

Public class densityutil {/*** convert the unit from Dp to PX (pixel) */public static int dip2px (context, float dpvalue) based on the cell phone resolution) {final float scale = context. getresources (). getdisplaymetrics (). density; Return (INT) (dpvalue * scale + 0.5f);}/*** based on the resolution of the phone) to DP */public static int px2dip (context, float pxvalue) {final float scale = context. getresources (). getdisplaymetrics (). density; Return (INT) (pxvalue/scale + 0.5f );}}

When using this tool, you only need to convert the pixel value through this tool class.

For example, if I want to place IV in the 30dip position of linearlayout, I need to convert 30dip to pix.

It can be used as follows: linearlayout. addview (IV, destinyutil. dip2px (getapplicationcontext (), 30,30 );

In this way, under different resolutions, the display is 30dip. As for the number of pix, the ghost will take care of it and let it go. Haha.

The adaptation problem is solved in this way!

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.