LinearLayout的layout_weight给适配带来了很多方便, 但有些新司机不是很了解父布局中还可以设置一个weightSum属性
<?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="wrap_content"
android:background="@color/colorAccent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Weight" />
</LinearLayout>
如果LinearLayout 中没有android:weightSum=”2”这句
Button宽度将充满整个LinearLayout, 有了这个后, 无论横竖屏, 都刚好是父布局宽度的一半.
也就是, 如果不指定父布局的android:weightSum, 则以所有子视图的 layout_weight 属性的累加值作为总和的最大值。如果指定了, 则总的就是我们指定的值.
如上面, 指定了2, 子控件是1, 那么子控件为父容器的一半.

本文详细解析了LinearLayout中的weightSum属性如何影响子View的布局。通过一个具体示例展示了当设置了weightSum值后,子控件如何根据该属性值来分配空间,从而实现不同屏幕尺寸下的自适应布局。
213

被折叠的 条评论
为什么被折叠?



