Android LinearLayout布局中 layout_weight解析

在LinearLayout的布局中,为了使各个控件能够按比例排放,一般会设置 layout_width="match_parent",并给layout_weight赋予一个值。

由于Android系统在对控件的宽度进行计算时,并不是按比例计算的,所以除此设置时会比较困扰,现在有一个很简单公式。


比如有4个控件,并排放置,并且想使它们的宽度比例为1:1:1:2,那么我们在计算layout_weight是,首先将它们相加得到5,然后分别减去它们的比例,即5-1=4,5-1=4,5-1=4,5-2=3,那么这四个控件的layout_weight分别为4,4,4,3.



<?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" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="100dp"> <LinearLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textSize="16sp"/> <TextView android:id="@+id/author" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> <TextView android:id="@+id/time" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> <TextView android:id="@+id/need" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textColor="@color/gray"/> </LinearLayout> <com.google.android.material.button.MaterialButton android:layout_width="60dp" android:layout_height="100dp" android:layout_marginHorizontal="12dp" app:cornerRadius="6dp" android:textSize="20sp" android:text="报名" android:textStyle="bold"/> </LinearLayout> 如何解决Indicates how much of the extra space in the LinearLayout is allocated to the view associated with these LayoutParams. Specify 0 if the view should not be stretched. Otherwise the extra pixels will be pro-rated among all views whose weight is greater than 0.
最新发布
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值