Android中的android:layout_weight使用详解
程序员文章站
2023-10-19 13:41:17
在使用linearlayout的时候,子控件可以设置layout_weight。layout_weight的作用是设置子空间在linearlayout的重要度(控件的大小比...
在使用linearlayout的时候,子控件可以设置layout_weight。layout_weight的作用是设置子空间在linearlayout的重要度(控件的大小比重)。layout_weight的值越低,则控件越重要。若不设置layout_weight则默认比重为0。
如果在一个linearlayout里面放置两个button,button1和button2,button1的layout_weight设置为1,button2的layout_weight设置为2,且两个button的layout_width都设置为fill_parent。
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button1"/>
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="button2"/>
</linearlayout>
则button1占据屏幕宽度的三分之二,而button2占据三分之一,如下图所示:
如果两个button的layout_width都设置成wrap_content,则情况刚好相反。button1占三分之一,button2占三分之二,如下图所示:
layout_weight在使用linearlayout设计复杂的布局时还是挺有用处的,例如,在水平的线性布局中,你要分足够的空间给控件1,剩下的空间则分配给控件2,则只要设置控件1的layout_width设置为wrap_content,不用设置layout_weight,而在控件2中,设置layout_width为fill_parent,layout_weight为1即可实现。
如果在一个linearlayout里面放置两个button,button1和button2,button1的layout_weight设置为1,button2的layout_weight设置为2,且两个button的layout_width都设置为fill_parent。
复制代码 代码如下:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="button1"/>
<button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="button2"/>
</linearlayout>
则button1占据屏幕宽度的三分之二,而button2占据三分之一,如下图所示:
如果两个button的layout_width都设置成wrap_content,则情况刚好相反。button1占三分之一,button2占三分之二,如下图所示:
layout_weight在使用linearlayout设计复杂的布局时还是挺有用处的,例如,在水平的线性布局中,你要分足够的空间给控件1,剩下的空间则分配给控件2,则只要设置控件1的layout_width设置为wrap_content,不用设置layout_weight,而在控件2中,设置layout_width为fill_parent,layout_weight为1即可实现。
上一篇: Android 加密解密字符串详解
推荐阅读
-
Android音频系统AudioTrack使用方法详解
-
Android自带的四种线程池使用总结
-
Android编程使用pull方式解析xml格式文件的方法详解
-
Android中检查网络连接状态的变化无网络时跳转到设置界面
-
详解Android获取系统内核版本的方法与实现代码
-
详解Python2.x中对Unicode编码的使用
-
Android AOP框架AspectJ使用详解
-
Android中自定义的dialog中的EditText无法弹出输入法解决方案
-
Android中使用LayoutInflater要注意的一些坑
-
Android开发教程之Fragment定义、创建与使用方法详解【包含Activity通讯,事务执行等】