如何使用Layout Weights让LinearLayout与Switch占据等宽空间
问题根源
水平LinearLayout的权重分配逻辑和Switch默认测量规则冲突,才会出现宽度分配不符合预期的问题:
- 当水平布局的子控件设置
layout_width="match_parent"时,系统会先计算所有子控件自身的默认测量宽度,再把父容器扣掉这些宽度后的剩余空间,按权重比例分配给子控件。Spinner默认最小宽度较大,初始测量后剩余空间分配完刚好能呈现各占一半的效果;但Switch默认测量宽度很小,初始测量阶段内部的LinearLayout已经占满了整行宽度,没有剩余空间可分配,最终就会出现LinearLayout占满全宽、Switch被挤压的情况。
修复方法
将两个子控件(内部垂直LinearLayout、Switch)的layout_width属性从match_parent修改为0dp即可,这是水平LinearLayout按权重分配宽度的标准写法:宽度设为0dp后,系统会跳过子控件初始宽度测量的步骤,直接把父容器的全部可用宽度按照weightSum和子项layout_weight的比例划分,完全不受控件本身默认测量宽度的影响。
修正后的核心布局代码:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/black" android:orientation="horizontal" android:weightSum="2" android:padding="5dp" android:layout_margin="4dp"> <LinearLayout android:layout_weight="1" android:orientation="vertical" android:layout_width="0dp" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAlignment="center" android:text="Playback Speed" android:textColor="#FFF" android:textSize="17sp" android:textStyle="bold" android:layout_gravity="center"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAlignment="center" android:text="@string/speed" android:textColor="#FFF" android:textSize="10sp"/> </LinearLayout> <Switch android:layout_weight="1" android:layout_gravity="center" android:id="@+id/speeds" android:layout_width="0dp" android:layout_height="wrap_content"/> </LinearLayout>
补充优化建议:布局中文字大小建议使用
sp作为单位而非dp,sp会跟随系统字体缩放设置自动调整,适配体验更好。
内容的提问来源于stack exchange,提问作者TechGeek
相关产品推荐
相关产品推荐

