版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/u010046908/article/details/48802909
标題:Android百分比布局初探
依賴庫:——com.android.support:percent
實作原理:
在這個包裡面有兩個新的容器類
1、PercentRelativeLayout
2、PercentFrameLayout
在此看來,這兩個類很顯然是繼承自 FrameLayout和
RelativeLayout兩個容器類。
新的容器有了一些設定百分比的屬性,下面我們來了解一下:
- layout_widthPercent
設定控件寬度為父容器的寬的百分比
- layout_heightPercent
設定控件高度為父容器的高的百分比
- layout_marginPercent
- layout_marginLeftPercent
設定控件與左邊控件的距離為父容器的寬度的百分比
- layout_marginTopPercent
設定控件與上方控件的距離為父容器的高度的百分比
- layout_marginRightPercent
設定控件與右邊控件的距離為父容器的寬度的百分比
- layout_marginBottomPercent
設定控件與下方控件的距離為父容器的高度的百分比
- layout_marginStartPercent
與上面的說明類似
- layout_marginEndPercent
從命名的方式我們可以知道,原來用某些具體機關(如dp)的設定現在都可以用百分比的方式進行設定了,例如設定控件的寬度layout_width原來我們是這樣玩的android:layout_width="match_parent"現在用了百分比的屬性之後呢,可以這樣玩了app:layout_widthPercent="50%",這裡的百分比是相對于父容器而言的。
官方文檔位址:https://juliengenoud.github.io/android-percent-support-lib-sample/
官網代碼:
1.
PercentFrameLayout
<android.support.percent.PercentFrameLayout
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"/>
<ImageView
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout/>
2.PercentRelativeLayout
<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">
<View
android:id="@+id/top_left"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:background="#ff0000"
app:layout_heightPercent="30%"
app:layout_widthPercent="70%" />
<View
android:id="@+id/top_right"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/top_left"
android:background="#00ff00"
app:layout_heightPercent="30%"
app:layout_widthPercent="30%" />
<View
android:id="@+id/centre"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/top_left"
android:background="#0000ff"
app:layout_marginLeftPercent="10%"
app:layout_marginRightPercent="20%"
app:layout_marginTopPercent="10%"
app:layout_marginBottomPercent="10%"
app:layout_heightPercent="40%" />
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/bottom"
android:layout_below="@+id/centre"
android:background="#00f0ff"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:layout_heightPercent="10%"/>
</android.support.percent.PercentRelativeLayout>
效果: