在安卓开发中,会经常遇到屏幕适配问题,下面总结一下,处理这问题的方法.
解决方法:
手机选择:
首先在项目开始时候,应该选择什么屏幕大小的手机,进行开发呢?
用当前市场上主流屏幕的手机,比如 1280*720
项目后期:还需要用不同分辨率手机进行测试:比如:480*800 1920*1000
图片适配:
做法:在工程目录:drawable目录中的不同目录,目录不同可以优先对应适配的手机
注释:480*800代表分辨率,括号中1.5代表屏幕密度
通常情况下,把图片放在drawalbe-hdpi目录,如果每个目录都放一份图片,那样会造成整个应用会占用太多资源
布局适配:
做法:不要绝对布局,多用相对布局或线性布局权重,用dp,不要px
权重适配:
做法:是在线性布局中处理 android:weihtSum
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="5"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#0f0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:background="#00f" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#f0f" />
</LinearLayout>
效果:
尺寸适配:
dx和dp关系:dp = px/设备密度
//设备密度,和手机分辨率有关
Int density = getResouces().getDisplayMetris().density;
问题:当遇到dp解决不了的问题,比如下面代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#00f" />
<TextView
android:layout_width="320dp"
android:layout_height="100dp"
android:background="#0f0" />
</LinearLayout>
解决方法:利用values目录下创建dimens.xml,这个目录定义了320*480的尺寸
创建values-720*1280目录,在这个目录也创建dimens.xml,这个文件定义了720*1280的尺寸
values目录下的dimens.xml
<resources>
<dimen name="textWith">160dp</dimen>
</resources>
value-720*1280目录下的dimens.xml
<resources>
<dimen name="textWith">320dp</dimen>
</resources>
代码适配:
Int width = getWindowManager().getDefaultDisplay().getWidth();
Int height = getWindowManager().getDefaultDisplay().getHeight();
TextView tv1 = (TextView)findViewById(R.id.tv1);
TextView tv2 = (TextView)findViewById(R.id.tv2);
LayoutParams params = new LayoutParams(width /3,height*0.2);
tv1.setLayoutParams(params);
tv2.setLayoutParams(params);