Android百分比布局

来源:互联网 发布:python帮助文档 编辑:程序博客网 时间:2024/05/16 11:37

2015的google大会发布了百分比布局,大大减少了android开发的适配量,最近使用了下百分比布局。


首先要引入百分比布局支持库:

新建一个工程,在xml中添加如下代码:
需要注意,百分比布局要加入下面这行代码

<span style="color:#FF6600;">xmlns:app="http://schemas.android.com/apk/res-auto"</span>

<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"></android.support.percent.PercentRelativeLayou
在布局中添加如下三个view:

<pre name="code" class="html"><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">    <TextView        android:id="@+id/tv1"        android:layout_width="0dp"        android:layout_height="0dp"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="10dp"        android:background="#ff4040"        app:layout_heightPercent="20%"        app:layout_widthPercent="70%"        android:gravity="center"        android:text="tv1 父容器为屏幕"/>    <TextView        android:id="@+id/tv2"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_below="@id/tv1"        android:background="#00ff00"        app:layout_heightPercent="30%"        app:layout_marginBottomPercent="10%"        app:layout_marginLeftPercent="10%"        app:layout_marginRightPercent="20%"        app:layout_marginTopPercent="10%"        android:gravity="center"        android:text="tv2 父容器为屏幕"/>    <android.support.percent.PercentRelativeLayout        android:background="#000000"        android:layout_width="match_parent"        android:layout_height="200dp"        android:layout_below="@id/tv2">        <TextView            android:id="@+id/tv3"            android:background="#00F3FF"            android:layout_width="0dp"            android:layout_height="0dp"            android:layout_centerInParent="true"            app:layout_heightPercent="20%"            app:layout_widthPercent="70%"            android:gravity="center"            android:text="tv3 父容器为黑色部分"            />    </android.support.percent.PercentRelativeLayout></android.support.percent.PercentRelativeLayout>


运行:


经验证发现此百分比是基于父容器。

0 0