有很多方法可以将View放到合适的位置,比如有两个view,一个view宽度占父控件的1/3,另一个占2/3,很自然的想到利用layout_weight属性,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_green_light"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="@android:color/holo_blue_light"
/>
</LinearLayout>
但是有个不爽的地方,就是每次使用比重的时候,都要将对应的控件用一层LinearLayout包起来,这样才可以计算权重,本来使用RelativeLayout 可以减少一些层级的套用,但是为了使用layout_weight ,必须加在其中嵌套一层LinearLayout,这样无疑又多了一层套用,对view的绘制速度肯定有影响。所以有了Percent Support Library,提供了PercentFrameLayout 和PercentRelativeLayout,可以直接以百分比的形式(占用PercentFrameLayout或者PercentRelativeLayout的比例)直接指定view的尺寸和margin
为了使用必须 在build.gradle 文件增加如下的依赖:
compile 'com.android.support:percent:23.0.0'
<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="#ff44aacc"
app:layout_heightPercent="20%"
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="#ffe40000"
app:layout_heightPercent="20%"
app:layout_widthPercent="30%" />
<View
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/top_left"
android:background="#ff00ff22"
app:layout_heightPercent="80%" />
</android.support.percent.PercentRelativeLayout>
由于这个库并不是标准的Android Library的一部分,所以使用了一个自定义的命名空间:“app”,在使用下面这些属性的时候要用自定义的命名空间,而不是android,这点要注意。
支持百分比的属性有:
1. layout_widthPercent
2. layout_heightPercent
3. layout_marginPercent
4. layout_marginLeftPercent
5. layout_marginTopPercent
6. layout_marginRightPercent
7. layout_marginBottomPercent
8. layout_marginStartPercent
9. layout_marginEndPercent
如果使用了layout_widthPercent这些属性,那么layout_width/height就不是必须要指明的,为了以防百分比所占的空间小于空间的内容,可以增加layout_width/height=”wrap_content”,这个时候利用wrap_content规则重新计算尺寸定位。