文章大纲
一、屏幕适配是什么
二、 重要概念讲解
三、屏幕适配实战
四、项目源码下载
一、屏幕适配是什么
??Android中屏幕适配就是通过对尺寸单位、图片、文字、布局这四种类型的资源进行合理的设计和规划,在布局时合理利用各种类型的资源,让布局拥有适应能力,能在各种设备下保持良好的展现效果。
二、常见屏幕适配方法介绍
1 屏幕尺寸
??屏幕尺寸是指屏幕对角线的长度,单位是英寸,1英寸=2.54厘米
2 屏幕分辨率
??屏幕分辨率是指横纵向上的像素点数,单位是px,1px=1个像素点,一般以纵向像素横向像素,如19201080,分辨率越高,显示效果越好。
3 屏幕像素密度
??屏幕像素密度是指每英寸上的像素点数,单位是dpi,屏幕像素密度与屏幕尺寸和屏幕分辨率有关。
4. px、dp、sp
(1)安卓里面获取屏幕宽和高,也是以px作为单位的。
(2)在160dpi(即分辨率是480*320)基准下,1dip=1px(也就是px不能适配所有机型),如下图所示,要充满屏幕,箭头的px值是不一样的。1dp=那个机型dpi/160px。所以用dp会比px好。
(3)在使用sp(设置文字的)时候,使用偶数,不要使用奇数或者小数,最最推荐的是12.14.18,22sp的文字大小(尽量不要使用12sp以下的大小,用户可能看不清楚)。
5. mdpi,hdpi,xdpi,xxdpi
安卓软件运行时,会自动根据屏幕像素去不同文件夹加载对应图片。
三、屏幕适配实战
1. 使用dp设置控件大小,sp设置字体大小(不可行)
activity_main2.xml布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:layout_width="200dp" android:layout_height="50dp" android:textSize="20sp" android:text="按钮1"/> <Button android:layout_width="200dp" android:layout_height="50dp" android:layout_marginTop="20dp" android:textSize="20sp" android:text="按钮2"/> </LinearLayout>
运行结果如下:
得出结论:即使使用dp设置控件大小,sp设置字体大小,也是无法适配所有手机的。因为这是谷歌自己的一个标准。dp是根据屏幕像素和分辨率一起来解决的。但是有些手机像素和分辨率不是对应关系,所以不行。
2. weight属性使用
activity_main3.xml布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" android:text="按钮1"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:textSize="20sp" android:text="按钮2"/> </LinearLayout>
运行结果如下:
得出结论:采用weight,可以使得组件按屏幕大小进行放大缩小,weight的计算方式如下:
如果将xml中的android:layout_weight属性值1和2互换,则结果是相反的,有兴趣伙伴可以下载源码看看效果。
3. 使用自动拉伸位图.9图
什么是.9图
??因为Android有太多的分辨率了,当圆角矩形控件在被拉伸放大的时候,圆角的部分就会出现模糊的情况。而点九切图就不同,它可以保证不管你上下还是左右拉伸,放大都可以保持原有的清晰度。
.9图存放位置
4. 屏幕方向限定符large
??比如我们想在屏幕竖屏时候加载什么布局,在屏幕横线时候加载什么布局。在手机加载什么布局,在平板电脑加载什么布局。
??该文章暂不展开讨论,将在Fragment使用中进行讲解。
5.多文件适配(重要)
??大家经过上面的学习之后,已经知道有些手机像素和分辨率不是对应关系,无法使用dp等单位来解决,那么我们可以以某个常