android layout_weight讲解

XML Android

1.当控件的属性android:layout_width="fill_parent"时,布局文件如下:

Xml代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <Buttonandroid:layout_width="fill_parent"
  6. android:layout_height="wrap_content"android:layout_weight="1"
  7. android:text="Button1"/>
  8. <Buttonandroid:layout_width="fill_parent"
  9. android:layout_height="wrap_content"android:layout_weight="2"
  10. android:text="Button2"/>
  11. </LinearLayout>

在这里Button1的Layout_weight=1,Buttong2的Layout_weight=2,运行效果为:


我们看到,Button1占了2/3,Button2占了1/3。如果此时把button2的weight设置成2000,不是说Button2就消失了,而是Button1的宽度几乎占满了屏幕宽度,而屏幕最后一丝细条则是留给Button2的,已近非常小了,没有显示出来。截图如下:





得出结论在layout_width设置为fill_parent的时候,layout_weight代表的是你的控件要优先尽可能的大,但尽可能大是有限度的,即fill_parent.

2.当控件的属性android:layout_width="wrap_content"时,布局文件如下:

Xml代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <Buttonandroid:layout_width="wrap_content"
  6. android:layout_height="wrap_content"android:layout_weight="1"
  7. android:text="Button1"/>
  8. <Buttonandroid:layout_width="wrap_content"
  9. android:layout_height="wrap_content"android:layout_weight="2"
  10. android:text="Button2"/>
  11. </LinearLayout>

同样,Button1的weight设置为1,Button2的weight设置为2,但是效果与fill_parent的效果截然相反。运行效果如下:


这时,和fill_parent正好相反,Button1的宽度占据了屏幕宽度的1/3,而Button2的宽度占据了屏幕的2/3,如果此时把Button1的weight设置为2000,按照之前理解,Button1应该小的几乎在屏幕上看不到,但是错了,实验告诉我们,当Button1的weight非常小时,也要"wrap_content",也就是要保证Button1至少能够显示。以下是Button1设置weight为2000时的运行截图:


我们看到,Button1已经足够小,但是要保证他能显示出来,因此得出结论:

在layout_width设置为wrap_content的时候,layout_weight代表的是你的控件要优先尽可能的小,但这个小是有限度的,即wrap_content.

当了解这些后,我们再设计程序时,为了能够自适应屏幕,不想给控件一个指定的宽度和高度,就可以使用这个weight属性来让它按自己比例来划分屏幕高度或者宽度了。

更多相关文章

  1. Android屏幕分辨率正确获取及PX,DPI,DP,SP等的对应关系
  2. 三、安卓UI学习(1)
  3. Android系统配置数据库注释(settings.db)
  4. android用户界面之按钮(Button)教程实例汇
  5. 在Fragment中设置控件点击方法,执行失败。
  6. TabHost与RadioGroup结合完成的菜单【带效果图】5个Activity
  7. android 分辨率及密度详细
  8. Android常用控件
  9. android用户界面-组件Widget-画廊视图Gallery

随机推荐

  1. Android(安卓)Socket网络通信
  2. Android(安卓)RecyclerView横向滑动
  3. Android编译系统详解(一)
  4. Android中获取正在运行的应用程序-----Ac
  5. Android(安卓)分析ANR和死锁
  6. Eclipse 开发 Android, Hello, DatePicke
  7. android 获取和设置屏幕亮度
  8. Android(安卓)studio gradle 多渠道打包
  9. Android(安卓):我的奇怪BUG:WindowManager$
  10. C# and android