在Android开发中比较头疼的是Android的分辨率问题,那么这里给大家介绍个万能办法,这个办法的优点是可以实现万能适应,给开发和美工设计提供了依据,但是对开发来说代码量也不少,具体办法你听我来说:
(1)获取屏幕的尺寸
1 |
WindowManager
windowManager = (WindowManager) |
2 |
getSystemService(Context.WINDOW_SERVICE); |
3 |
Display
d = windowManager.getDefaultDisplay(); |
5 |
mHeight
= d.getHeight(); |
6 |
DisplayMetrics
dm = getResources().getDisplayMetrics(); |
7 |
mScreenDensity
= dm.density; |
(2)美工设计图的尺寸
uiWidth,uiHeight
(3)获取缩放比例
1 |
float scaleWidth
= mWidth / uiWidth; |
2 |
float scaleHeight
= mHeight/ uiHeight; |
(4)所有布局的尺寸用代码实现:
01 |
public static int getWidthSize( int size){ |
02 |
return ( int )
(size * scaleWidth); |
05 |
public static int getHightSize( int size){ |
06 |
return ( int )
(size * scaleHeight); |
09 |
public static float getTextSize( int pxSize){ |
10 |
return (pxSize*scaleHeight)
/ mScreenDensity; |
13 |
public static void setViewSize( int width, int height,
View v){ |
14 |
int paramWidth
= getWidthSize(width); |
15 |
int paramHeight
= getHightSize(height); |
16 |
ViewGroup.MarginLayoutParams
params |
17 |
=
(ViewGroup.MarginLayoutParams)
v.getLayoutParams(); |
18 |
if (width
!= INVALID){ |
19 |
params.width
= paramWidth; |
21 |
if (height
!= INVALID){ |
22 |
params.height
= paramHeight; |
24 |
v.setLayoutParams(params); |
27 |
public static void setViewPadding( int left, int top, int right, int bottom, |
29 |
left
= getWidthSize(left); |
30 |
top
= getHightSize(top); |
31 |
right
= getWidthSize(right); |
32 |
bottom
= getWidthSize(bottom); |
33 |
v.setPadding(left,
top, right, bottom); |
37 |
public static void setViewMargin( int left, int top, int right, int bottom, |
39 |
int paramLeft
= getWidthSize(left); |
40 |
int paramTop
= getHightSize(top); |
41 |
int paramRight
= getWidthSize(right); |
42 |
int paramBottom
= getHightSize(bottom); |
43 |
ViewGroup.MarginLayoutParams
params = (ViewGroup.MarginLayoutParams) |
46 |
params.leftMargin
= paramLeft; |
48 |
if (right
!= INVALID){ |
49 |
params.rightMargin
= paramRight; |
52 |
params.topMargin
= paramTop; |
54 |
if (bottom
!= INVALID){ |
55 |
params.bottomMargin
= paramBottom; |
57 |
v.setLayoutParams(params); |
(5)这里是设置尺寸的代码:
1 |
setViewSize( 100 , 100 ,
mView); |
2 |
setViewMargin( 20 , 0 , 0 , 20 ,
mView); |
3 |
setViewPadding( 10 , 10 , 10 , 10 ,
mView); |
4 |
mTextView.setTextSize(getTextSize( 30 )); |
由上在设计效果图时,可对图内元素进行尺寸标注,程序即可实现按比例缩放。
Android万能分辨率适应法,码迷,mamicode.com