屏幕适配?看完你就会知道,原来一切都是那么简单
到底需要怎么做呢?
首先先让我们了解一下android都有哪些尺寸介绍和意义及用法:
- dp
- px
- sp
- dpi
- pt
就算不知道确切含义,相信对于以上这几种尺寸单位大家也都比较脸熟,这里先让我们重新认识一下它们:
dp (dip): 即设备无关像素(device independent pixels),这种尺寸单位在不同设备上的物理大小相同。
px:即像素(pixel),这个不用多说。
pt:通常用来作为字体的尺寸单位,1 pt相当于1/72英寸。
dpi:像素密度,1 英寸约等于2.54厘米,主要用来描述手机屏幕的单位长度中的像素密度。
sp:大部分人只知道它通常用作字体的尺寸单位,实际大小还与具体设备上的用户设定有关。
可以从我们以前的经常使用的dp来说,这个单位对于物理屏幕相差不太大的时候并且结合这线性布局,可以完美的解决屏幕适配问题,但是一旦屏幕的物理属性相差过大的时候,一个布局在高分辨率的手机上和在低分辨率的手机上就会显示出极大的差别,所以我们可以想到,这并不是我们想要的结果,你会想到,既然这样,那么我们为什么不通过屏幕的百分比来进行控件的尺寸限定,这样对于屏幕适配体验感是极佳的,至于总有一些屏幕尺寸比较奇怪的,可能就不会有太完美的适配性了。
所以谷歌公司当然也想到了这样的解决办法,所以谷歌公司开发了支持百分比的布局方式了,先让我们了解这是一个什么库:
android-percent-support-lib:
该库提供了两种布局方式:
- PercentRelativeLayout、PercentFrameLayout,通过名字就可以看出,这是继承自FrameLayout和RelativeLayout两个容器类;
支持的属性有:
layout_widthPercent、layout_heightPercent、
layout_marginPercent、layout_marginLeftPercent、
layout_marginTopPercent、layout_marginRightPercent、
layout_marginBottomPercent、layout_marginStartPercent、layout_marginEndPercent。
可以看到支持宽高,以及margin。
所以看到这里,大家就可以知道,其实我们使用起来很简单,就是将PercentRelativeLayout、PercentFrameLayout替换FrameLayout、RelativeLayout即可。
对于谷歌公司为什么没有将LinearLayout也做成支持屏幕百分比的原因可能是因为线性布局存在weight属性吧。
下来我们就简单的介绍如何来定义布局吧:
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<TextView
android:id="@+id/row_one_item_one"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:background="#7700ff00"
android:text="aaa"
android:gravity="center"
app:layout_heightPercent="20%"
app:layout_widthPercent="70%"/>
<TextView
android:id="@+id/row_one_item_two"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_toRightOf="@+id/row_one_item_one"
android:background="#396190"
android:text="bbb"
app:layout_heightPercent="20%"
android:gravity="center"
app:layout_widthPercent="30%"/>
<ImageView
android:id="@+id/row_two_item_one"
android:layout_width="match_parent"
android:layout_height="0dp"
android:src="@drawable/pic1"
android:scaleType="centerCrop"
android:layout_below="@+id/row_one_item_one"
android:background="#d89695"
app:layout_heightPercent="70%"/>
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="@id/row_two_item_one"
android:background="#770000ff"
android:gravity="center"
android:text="ccc"
app:layout_heightPercent="10%"
app:layout_widthPercent="100%"/>
</android.support.percent.PercentRelativeLayout>