关于Android的layout_weight

来源:互联网 发布:工业视觉软件 编辑:程序博客网 时间:2024/05/21 01:30

先说总结:系统总是先按layout_width(或layout_height)分配长度,然后将布局中的剩余长度按layout_weight的比例分配。


不理解没关系,看示例:

1.一般我们设置layout_weight时都要设置layout_width(或layout_height)为”0dp”,这次我们不这么做,而是将属性设为match_parent。

代码如下:

<?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">    <View        android:layout_width="match_parent"        android:layout_height="100dp"        android:layout_weight="1"        android:background="@android:color/holo_red_light" />    <View        android:layout_width="match_parent"        android:layout_height="100dp"        android:layout_weight="2"        android:background="@android:color/holo_green_light" />    <View        android:layout_width="match_parent"        android:layout_height="100dp"        android:layout_weight="2"        android:background="@android:color/holo_blue_light" /></LinearLayout>

效果如下:
这里写图片描述

为什么会有这种效果呢?

首先,Android按layout_width要求来布局,假设当期那屏幕宽度为1080.

因为是match_parent,所以每个view都分配了1080的宽度,然后,再将剩余的空间按1:2:2的方式分配。

剩余空间为:1080-3*1080 = -2*1080;

故三个view的最终大小为:

第一个view:1080+(-2*1080/5*1) = 648

第二、三个view:1080+(-2*1080/5*2) = 216

故比例出现了如图中3:1:1的情况。


2.如果将layout_width属性设为wrap_content,原理同上。

代码如下:

<?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="wrap_content"        android:layout_height="100dp"        android:layout_weight="1"        android:background="@android:color/holo_red_light"        android:text="Android"        android:textSize="15sp" />    <TextView        android:layout_width="wrap_content"        android:layout_height="100dp"        android:layout_weight="2"        android:background="@android:color/holo_green_light"        android:text="Android"        android:textSize="15sp" />    <TextView        android:layout_width="wrap_content"        android:layout_height="100dp"        android:layout_weight="2"        android:background="@android:color/holo_blue_light"        android:text="Android"        android:textSize="15sp" /></LinearLayout>

效果如下:

这里写图片描述

可以看到,首先分配”Android”文字需要的空间,然后剩余空间按1:2:2分配,故除了”Andriod”文字外,每个TextView的剩余空间的比例是1:2:2。


到此,你应该明白了使用layout_weight时为什么要将layout_width(或layout_height)为”0dp”了吧。

0 0