在常用的布局LinearLayout, RelativeLayout, FrameLayout中,只有LinearLayout支持使用layout_weight属性来实现按比例指定控件大小的功能,其它两种布局都不支持。
为此,Android引入了一种全新的布局方式来解决这个问题——百分比布局。在这种布局中,我们可以不再使用wrap_content, match_parent等方式来指定控件的大小,而是允许直接指定控件在布局中所占的百分比。
由于LinearLayout本身已经支持按比例指定控件的大小了,因此百分比布局只为RelativeLayout和FrameLayout进行了功能扩展,即提供了PercentRelativeLayout和PercentFrameLayout两个全新的布局。
如何使用
- 打开app/build.gradle文件,在dependencies闭包中添加如下内容:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:percent:24.2.1'
}
- 示例:
<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">
<Button
android:id="@+id/button1"
android:text="Button 1"
android:layout_gravity="left|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button2"
android:text="Button 2"
android:layout_gravity="right|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button3"
android:text="Button 3"
android:layout_gravity="left|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<Button
android:id="@+id/button4"
android:text="Button 4"
android:layout_gravity="right|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
</android.support.percent.PercentFrameLayout>
说明:
PercentFrameLayout和PercentRelativeLayout分别继承了FrameLayout和RelativeLayout中所有属性,并且可以使用app:layout_widthPercent和app:layout_heightPercent来按百分比指定控件的宽高。