日常爬坑-android LinearLayout 设置weight无效

最近做开发时碰到一个诡异的问题,weight时,如果textview的内容不同,导致排版错乱。
如图所示:

image-20200721132828499

一、原因

查看官方对weight的说明,大概是如果不想拉伸时图,需要将相应的拉伸方向(宽或高)设置为0。如果宽或高不设置为0,那么多余的像素将在权重大于0的所有视图中按比例分配。

image-20200721133603185

检查下代码,发现我的横向的LinearLayout时,没有将宽度设置为0dp,因此就出现了控件被拉伸的情况。

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="题号"
android:textColor="@color/eink_black_color"
android:textSize="12sp"
android:textStyle="bold" />

二、解决

由于我需要的是固定的宽度,因此我只需要将横向的LinearLayout,中TextView的宽度改为为0dp便可。

当然,如果是竖向的LinearLayout,就需要将高度设置为0dp了。

<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="题号"
android:textColor="@color/eink_black_color"
android:textSize="12sp"
android:textStyle="bold" />

修改后的效果

image-20200721132704133

日常爬坑-android LinearLayout 设置weight无效

https://www.laoyuyu.me/2020/07/27/android/weight_invalid/

作者

AriaLyy

发布于

2020-07-27

许可协议

CC BY-NC-SA 4.0

评论