神奇的layout_weight属性

来源:互联网 发布:mac文件夹防止被删除 编辑:程序博客网 时间:2024/05/16 10:40

1、概述

        在线性布局有时候为了控制一下屏幕的适配,可以使用layout_weight这个属性来设置权重,要注意一点,这个属性只有在Linearlayout中才有效,这个属性往往会随着android:layout_width设置而变化,有时候可能出现一些意想不到的效果,下面来看看

2、实例效果

布局文件如下,水平放了2个文本,设置不同权重1:2

2.1、layout_width=“0dp”

<span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    tools:context=".MainActivity">    <TextView        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="aaa"        android:background="@android:color/holo_blue_bright"        android:textSize="20sp" />    <TextView        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="2"        android:background="@android:color/holo_green_dark"        android:text="bbb"        android:textSize="20sp" /></LinearLayout></span>

正常1:2权重显示布局



2.2、layout_width=“match_parent”

width改成match_parent

惊奇的发现,说好的1:2咋变成2:1了呢,

咋回事呢?下面会详细解释

2.3、layout_width=“wrap_content”

此时又恢复正常


3、解开谜底

【原则】Linearlayout中的layout_weight属性首先按照控件声明的尺寸进行分配,然后将剩下的尺寸按照weight分配

这里看出layout_width=“0dp”和layout_width=“wrap_content”是一样的,他们是把宽度交给实际控件的宽度起始都为0;

而layout_width=“match_parent”是将控件在一开始就设置成了父控件Linearlayout的大小假设为S,,俩个控件都是match_parent,则对应每个TextView控件一开始大小就为S

那个剩下的尺寸为:原屏幕尺寸减去控件占有尺寸,即S-(S+S)= -S ;此时第一个TextVIew占1/3权重,则实际宽度为S+(-S)*1/3 = S* 2/3,同理可知第二个TextView占S*1/3。

这下谜底解开了吧。Google在官方推荐,当使用layout_weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。


4、其他

单一控件实现权重布局

如果我们只有一个TextView要想实现这一个控件占1/2权重怎么办?此时没有其他控件跟我们均分,此时可以在Linearlayout中将android:weightSum="2",然后在texiview中权重设置为1即可

布局文件为

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    android:weightSum="2"    tools:context=".MainActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_weight="1"        android:background="@android:color/holo_blue_bright"        android:text="aaa"        android:textSize="20sp" /></LinearLayout>

效果图为


0 0
原创粉丝点击