您的位置:首页 > 移动开发 > Android开发

在android布局中使用layout_weight的几点技巧和说明layout_weight

2015-09-25 18:44 781 查看

layout_weight的使用情形

在开发android应用程序时,经常需要根据不同的宽度来等分某个线性布局,使得在这个区域中,几个view按照一定的比例来排列,一般等分比较常见。

以等宽举例说明:

由于一套布局需要适配多种不同型号的android机器,因此在布局文件中将view尺寸写死是一种下下之策,这时,layout_weight就派上了用场。

布局文件关键代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/button1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#44555555"
android:gravity="center"
android:text="1" />

<Button
android:id="@+id/button2"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#66555555"
android:gravity="center"
android:text="2" />

<Button
android:id="@+id/button3"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#88555555"
android:gravity="center"
android:text="3" />

<Button
android:id="@+id/button4"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#aa555555"
android:gravity="center"
android:text="4" />

<View
android:id="@+id/view"
android:layout_width="0dip"
android:layout_height="10dip"
android:layout_weight="1"
android:background="#aa550000" />

</LinearLayout>

显示效果如下:



四个按钮以及最右侧view的layout_weight均为1

外层的LinearLayout默认的是水平方向布局,因此,当在这种ViewGroup布局中添加children时,若想使得children宽度一致或者按照比例显示,那么需要添加两行代码:

android:layout_width="0dip"
android:layout_weight="1"

同理,如果是纵向排列的linearlayout布局,则需要使用

android:layout_height="0dip"
android:layout_weight="1"

这样children就会在纵向按照等高排列。

有时候会遇到这样的需求:动态的隐藏第2个button,同时让右侧的view向左侧对齐,但宽度与原来设定的一致。

当仅仅gone掉第2个button,会出现下面的效果



这时,所有的button会重新刷新并进行layout,button2是消失了,但是其他控件的宽度也改变了,这是因为gone掉的view不占空间,整个横向排列的总weight减一,在每个控件的layout_weight值不变的情况下,所占比重均增加了,不符合需求。

那么将button2设置为invisible可以吗?同样不符合需求,invisible的view是看不到的,但是仍然与原来占据同样的空间。

一种解决方案:在最右侧添加一个view,即上图的红色区域。为了演示方便,我将view的高度设定位10dip,如果不想显示此view,可以将高度设为0dip,这样,由于这个view

宽度不为0,因此会占据着一定空间。

当隐藏第2个button时,使用如下代码,调整最右侧view的weight,从而重新调整布局文件

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, 0);
params.weight = 2;
view.setLayoutParams(params);

效果如图:



代码说明:

LinearLayout.LayoutParams(0, 0);

传入的这两个参数分别为想要修改后的控件宽度和高度,由于需要设置weight参数,因此必须要将宽度设置为0.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: