layout_weight
该属性的作用是决定控件在其父布局中的显示权重,一般用于线性布局中。其值越小,则对应的layout_width或layout_height的优先级就越低,一般横向布局中,决定的是layout_width的优先级;纵向布局中,决定的是layout_height的优先级。
传统的layout_weight使用方法是将当前控件的layout_width和layout_height都设置成fill_parent,这样就可以把控件的显示比例完全交给layout_weight;这样使用的话,就出现了layout_weight越小,显示比例越小的情况。不过对于2个控件还好,如果控件过多,且显示比例也不相同的时候,控制起来就比较麻烦了,毕竟反比不是那么好确定的。
举例说明,如果parent长度是10,模式是horizontal,三个子控件的layout_weight分别是1,1,3,那么这三个子控件的宽度就分别是2、2、6,也就是按照layout_weight的比例来分配的。
实际举例:
布局文件:style(style_layout.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 全屏拉伸 -->
<style name="layout_full">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>>
</style>
<!-- 固定自身大小 -->
<style name="layout_wrap">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
<!-- 横向分布 -->
<style name="layout_horizontal" parent="layout_full">
<item name="android:layout_width">0px</item>
</style>
<!-- 纵向分布 -->
<style name="layout_vertical" parent="layout_full">
<item name="android:layout_height">0px</item>
</style>
</resources>
主界面布局文件如下(activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/layout_full"
android:orientation="vertical" >
<LinearLayout
style="@style/layout_vertical"
android:layout_weight="1"
android:orientation="horizontal">
<View
style="@style/layout_horizontal"
android:background="#aa0000"
android:layout_weight="1"/>
<View
style="@style/layout_horizontal"
android:background="#00aa00"
android:layout_weight="2"/>
<View
style="@style/layout_horizontal"
android:background="#0000aa"
android:layout_weight="4"/>
<View
style="@style/layout_horizontal"
android:background="#aaaaaa"
android:layout_weight="8"/>
</LinearLayout>
<LinearLayout
style="@style/layout_vertical"
android:layout_weight="2"
android:orientation="vertical" >
<View
style="@style/layout_vertical"
android:background="#ffffff"
android:layout_weight="8"/>
<View
style="@style/layout_vertical"
android:background="#aa0000"
android:layout_weight="4"/>
<View
style="@style/layout_vertical"
android:background="#00aa00"
android:layout_weight="2"/>
<View
style="@style/layout_vertical"
android:background="#0000aa"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
根据上面的分配关系,可以得出最终的占比效果为:

布局权重在Android中的应用
本文详细解释了Android布局中的layout_weight属性,并通过实例展示了如何使用它来控制控件的显示比例,包括横向和纵向布局的分配关系。
2357

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



