為什么使用百分比布局
由于Android系統(tǒng)的碎片化發(fā)展導致了市面上多種分辨率、多種屏幕密度共存诬滩,這對我們的屏幕適配增加了不少的難度,在布局方面我們都知道可以通過LinearLayout的layout_weight屬性來進行適配,但是在某些情況下我們要向用這種方法進行適配就必須進行多層布局嵌套友驮,而這則會導致布局文件復雜,增加渲染層次驾锰,致使性能下降卸留。針對這種情況google為我們提供了一個百分比布局兼容庫:Android Percent Support Library路翻,解決了上述的問題桑腮,目前它支持RelativeLayout和FrameLayout的百分比布局,不過已經(jīng)有大牛在GitHub上面開源了LinearLayout的百分比布局支持庫厦取。
如何使用百分比布局
1.添加依賴
dependencies {
...
implementation 'com.android.support:percent:27.0.2'
}
2.屬性講解
在函數(shù)庫里面我們主要用到兩個類:
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的寬高比
3.實例演示(以PercentRelativeLayout為例)
這里由于不設置layout_width和layout_height的話Android Studio會報錯所以我們把它設置成0dp赏酥。
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/one"
android:background="#f0f000"
app:layout_heightPercent="30%"
app:layout_widthPercent="70%"
android:text="Hello World!"
/>
<TextView
android:layout_width="0dp"
android:layout_toRightOf="@id/one"
android:layout_height="0dp"
app:layout_heightPercent="30%"
app:layout_widthPercent="30%"
android:background="#ff0000"
android:text="Hello World!"
/>
<TextView
android:layout_width="0dp"
android:layout_below="@id/one"
android:layout_height="0dp"
app:layout_heightPercent="70%"
app:layout_widthPercent="100%"
android:background="#ff00ff"
android:text="Hello World!"
/>
</android.support.percent.PercentRelativeLayout>
效果圖
layout_aspectRatio屬性演示
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="100dp"
android:layout_height="0dp"
app:layout_aspectRatio="50%"
android:background="#ff00ff"
android:text="Hello World!"
/>
<TextView
android:layout_width="100dp"
android:layout_height="0dp"
android:layout_alignParentRight="true"
app:layout_aspectRatio="200%"
android:background="#0f00ff"
android:text="Hello World!"
/>
</android.support.percent.PercentRelativeLayout>
效果圖
最后編輯于 :2018.08.06 23:18:54
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者