Android官方支持百分比设置宽和高的控件及示例
非著名程序员
Android官方终于支持按百分比来设置控件的宽和高了。有了这样的控件,写起来就比较方便了。其实LinearLayout的layout_weight也能实现百分比效果,不过这个更直接,更好用。这个百分比控件的出现,其实在另一方面也解决了部分屏幕适配的问题。 这个库提供了两种布局供大家使用,分别为: PercentRelativeLayout和PercentFrameLayout,我们通过以往经验和名字就可以知道它们分别继承于RelativeLayout和FrameLayout两个容器类。 支持的属性如下:
layout_widthPercent、layout_heightPercent、
layout_marginPercent、layout_marginLeftPercent、
layout_marginTopPercent、layout_marginRightPercent、
layout_marginBottomPercent、layout_marginStartPercent、layout_marginEndPercent
运行效果如下:
使用说明: 1、首先记得在build.gradle添加: compile 'com.android.support:percent:22.2.0’ 2、布局文件如下:
<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/top_left"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:background="#ff44aacc"
android:gravity="center"
android:text="height:20,width:70"
app:layout_heightPercent="20%"
app:layout_widthPercent="70%" />
<TextView
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"
android:gravity="center"
android:text="height:20,width:30"
app:layout_heightPercent="20%"
app:layout_widthPercent="30%" />
<TextView
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/top_left"
android:background="#ff00ff22"
android:gravity="center"
android:text="height:80"
app:layout_heightPercent="80%" />
</android.support.percent.PercentRelativeLayout>
怎么样,很方便吧?快使用起来吧!