為什么使用百分比布局
由於Android系統的碎片化發展導致了市面上多種分辨率、多種屏幕密度共存,這對我們的屏幕適配增加了不少的難度,在布局方面我們都知道可以通過LinearLayout的layout_weight屬性來進行適配,但是在某些情況下我們要向用這種方法進行適配就必須進行多層布局嵌套,而這則會導致布局文件復雜,增加渲染層次,致使性能下降。針對這種情況google為我們提供了一個百分比布局兼容庫:Android Percent Support Library,解決了上述的問題,目前它支持RelativeLayout和FrameLayout的百分比布局,不過已經有大牛在GitHub上面開源了LinearLayout的百分比布局支持庫。
添加依賴:
//百分比布局依賴 compile 'com.android.support:percent:26.0.0-alpha1'
在函數庫里面我們主要用到兩個類:
- PercentRelativeLayout
- PercentFrameLayout
它們主要有以下屬性
- app:layout_heightPercent:用百分比表示高度
- app:layout_widthPercent:用百分比表示寬度
- app:layout_marginPercent:用百分比表示View之間的間隔
- app:layout_marginLeftPercent:用百分比表示左邊間隔
- app:layout_marginRight:用百分比表示右邊間隔
- app:layout_marginTopPercent:用百分比表示頂部間隔
- app:layout_marginBottomPercent:用百分比表示底部間隔
- app:layout_marginStartPercent:用百分比表示距離第一個View之間的距離
- app:layout_marginEndPercent:用百分比表示距離最后一個View之間的距離
- app:layout_aspectRatio:用百分比表示View的寬高比
實例:
<?xml version="1.0" encoding="utf-8"?> <android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" > <TextView android:layout_alignParentBottom="true" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FF4081" app:layout_heightPercent="100%" app:layout_marginPercent="4%" app:layout_widthPercent="10%" android:text="100%" android:gravity="center" /> <TextView android:layout_alignParentBottom="true" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/textView" android:background="#8FFF4081" app:layout_heightPercent="80%" app:layout_marginPercent="4%" app:layout_widthPercent="10%" android:text="80%" android:gravity="center" /> <TextView android:layout_alignParentBottom="true" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/textView1" android:background="#60FF4081" app:layout_heightPercent="60%" app:layout_marginPercent="4%" app:layout_widthPercent="10%" android:text="60%" android:gravity="center" /> <TextView android:layout_alignParentBottom="true" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/textView2" android:background="#40FF4081" app:layout_heightPercent="40%" app:layout_marginPercent="4%" app:layout_widthPercent="10%" android:text="40%" android:gravity="center" /> <TextView android:layout_alignParentBottom="true" android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/textView3" android:background="#20FF4081" app:layout_heightPercent="20%" app:layout_marginPercent="4%" app:layout_widthPercent="10%" android:text="20%" android:gravity="center" /> </android.support.percent.PercentRelativeLayout>