新建一个项目,修改XML如下:
其中Activity名称为:MyWeight
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyWeight">
<!-- vertical:垂直-->
<!-- horizontal:水平-->
<!-- weight 比重属性 (权重属性)-->
<!--注意线性布局layout_width="match_parent跟随父类,要不然宽度为0,显示不出来-->
<!--horizontal:水平 为权重属性的对象-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="20dp"
android:orientation="horizontal">
<!--权重为 90/(90+0+10)-->
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="90"
android:background="#ffff00" />
<!--权重为0-->
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:background="#00ff00" />
<!--权重为 10/(90+0+10)-->
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="10"
android:background="#0000ff" />
</LinearLayout>
<!--注意线性布局线性布设定好宽度后,注意设定TextView中的android:layout_width="match_parent"-->
<!--vertical:垂直 为权重属性的对象-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="vertical">
<!--权重为 1/(1+1+1)-->
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#cff000" />
<!--权重为 1/(1+1+1)-->
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#00ff00" />
<!--权重为 1/(1+1+1)-->
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#0000ff" />
</LinearLayout>
</LinearLayout>
运行界面如下:
要注意方向及宽高属性
android:orientation="horizontal
android:layout_width=“match_parent”
android:layout_height=“0dp”
占比权重程序注释中有计算公式。