Android百分比布局支持庫
雖然有很多的布局可以在 Android 應用程序開發的世界供我們使用,但我們總是只用這三種布局:LinearLayout, RelativeLayout and FrameLayout。
不管怎么說在用 RelativeLayout 和 FrameLayout 的時候總有一些問題,因為你不能設置子視圖的百分比程度。只有兩種方法可能做到,1. 布局在 LinearLayout 里并用它的 layout_weight 布局參數;2. 在 Java 代碼中重寫 onMeasure 方法來實現。
舉個例子,如果我想在 RelativeLayout 里放一個簡單的紅色矩形,它是在頂部,并且距離左邊的 5% 的位置,寬度為屏幕的25%。我們的代碼可以這樣寫:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="20"> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <View android:layout_width="0dp" android:layout_height="100dp" android:layout_weight="5" android:background="#ff0000" /> </LinearLayout> </RelativeLayout>
這是結果:
你會注意到這樣的代碼應該是非常復雜的。與此同時,這些控件也用視圖和 LinearLayout 填充著,我們可以把它們看成是一種浪費。
這將不再是一個問題啦,因為在前幾天 Android M 宣布了它的名字:棉花糖(Marshmallow),Android 團隊推出了許多支持庫去幫助開發者與碎片化的戰斗!其中之一就是 百分比支持庫(Percent Support Library) ,它具備的能力是用百分比去設置 RelativeLayout 和 FrameLayout 的尺寸!
你好,百分比支持庫
這個庫是非常容易使用的,因為它就如同 RelativeLayout 和 FrameLayout 一樣我們都熟悉,只是有一些額外的功能。
首先,因為百分比支持庫是隨著 Android Support Library 23 一起的,所請確保你已經在 SDK Manager 中的 Android Support Library 更新了最新的版本。然后在build.gradle文件中添加下面這樣的依賴:
compile 'com.android.support:percent:23.0.0'
現在,在使用老的 RelativeLayout 和 FrameLayout 做替換,只需要簡單的將他們各自切換到android.support.percent.PercentRelativeLayout和android.support.percent.PercentFrameLayout。這里有9個布局參數可以使用:
layout_widthPercent: 用百分比來表示寬度,比如:app:layout_widthPercent="25%"
layout_heightPercent: 用百分比來表示高度
layout_marginPercent: 用百分比來表示 Margin
其余的是用百分比來表示每個 margin 面layout_marginLeftPercent,layout_marginRightPercent,layout_marginTopPercent,layout_marginBottomPercent,layout_marginStartPercent,layout_marginEndPercent
用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 app:layout_widthPercent="25%" android:layout_height="100dp" app:layout_marginLeftPercent="5%" android:background="#ff0000" /> </android.support.percent.PercentRelativeLayout>
這是結果:
你可以看到結果是完全是一致的,而且具有更短更清晰的代碼,此外,該空間現在沒有填充其他布局,這就讓性能達到了更好的程度。
實際上這本應該就是 Android 整體的一部分,但不幸的是,事實并非如此。把它填加到原生Android 的RelativeLayout/FrameLayout 已經太遲了,因為用戶用的設備都是老的操作系統版本,不可能支持使用這個功能。所以這就是為什么 Android 團隊決定把它作為一個支持庫來發布,我支持這個主意。