Android布局设计中的layout_weight的学习
16lz
2021-01-23
Android布局设计中的layout_weight的学习
在Android XML文件的布局设计中,我们经常会遇到Android:layout_weight这个属性。从英文上的意思可以了解到,“weight”是指“分量、重要性”,即该属性指明了widget在设计布局中的重要性。那究竟layout_weight究竟是做什么用的呢?
在线性布局中(LinearLayout)中(默认android:orientation="horizontal"),我们可以使用layout_weight为其视图(View)包含的小组件(widget)或者是容器(container)指定填充权值(重要度)。既是我们可以允许视图中的widget按照layout_weight所指定的数值,按比例分配来填充屏幕的空间。如果我们不指定这个属性,则系统默认为0,此时它表示按照widgets实际大小来显示;若layout_weight大于0,则表明存放视图组件的容器空间会按每个组件的layout_weight的值来按比例分配。为了更好更直观地说明这个问题,我用之前做计算器的一部分XML代码来进行举例说明:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:background="#F000" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_vertical" > <EditText android:id="@+id/etResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:textSize="25sp" android:text="" android:layout_gravity="center" android:gravity="left" android:cursorVisible="true" android:layout_marginLeft="2dp" android:layout_marginRight="2dp" android:layout_marginTop="4dp" /> <TableLayout android:id="@+id/tablelayoyt" android:layout_marginTop="4dp" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/linearlayout02" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btnC" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25sp" android:text="@string/delete" android:layout_weight="2"/> <Button android:id="@+id/btnCE" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25sp" android:text="@string/deleteall" android:layout_weight="1"/> </LinearLayout> </TableRow> </TableLayout></LinearLayout>
1、 首先应让两个Button的layout_width="fill_parent"
第一个Button的layout_weight设置为“2”,第二个Button的layout_weight设置为“1”,运行结果如下:
从图中我们可以看到,第一个按钮的长度为第二个按钮长度的1/2,既是屏幕长度的1/3,以此类推。这也说明了,如果layout_width="fill_parent"时,layout_weight的值越小,则该widget占用的空间长度比例越高。
2、 让两个Button的layout_width="wrap_content"
第一个Button的layout_weight设置为“2”,第二个Button的layout_weight设置为“1”,运行结果如下:从此图可以看出,它与layout_weight=”fill_parent”完全相反。这说明了,如果layout_weight=”wrap_content”时,layout_weight的值越小,则该widget占用的空间长度比例越低。
3、 两个Button的layout_width属性相等,layout_weight="1"
如下图所示:从图中可以看出,两个Button的长度相同。这说明了,如果设计布局中的所有widget的layout_weight都相同,则它们会按照同样的比例来填充屏幕空间。
总结:如果我们希望布局中的widget或者container按照一定的比例来填充空间,我们可以使用layout_weight属性。但同时对于layout_weight,我们要知道当属性layout_width分别等于“fill_parent”和“wrap_content”时候的区别,从而适当地使用这个layout_weight属性来进行布局设计。更多相关文章
- Android 文件布局一些细节备忘
- android 虚拟按键遮挡布局
- android 线性布局几个属性
- Android布局文件的属性值解析
- Android LinearLayout的android:layout_weight属性
- android学习笔记(7)AbsoluteLayout+FrameLayout+RelativeLayout+