LinearLayout的两个关键属性(layout_gravity&weight)

来源:互联网 发布:电商运营 知乎 编辑:程序博客网 时间:2024/06/01 10:04

1、android:layout_gravity

      指定控件在布局中的对齐方式。当排列方向是vertical时,只有水平方向上的对齐方式才会生效;horizontal则相反。

       (android:gravity指定文字在控件中的对齐方式)

2、android:layout_weight

      使用比例的方式来指定控件大小。

      e.g.:水平排列的一个EditView和Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><EditTextandroid:id="@+id/input_message"android:layout_width="0dp"                  //规范写法,此时控件的宽度就仅由weight来决定android:layout_height="wrap_content"android:layout_weight="1"android:hint="Type something"/><Buttonandroid:id="@+id/send"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"                        //EditView和Button以1:1的比例水平排列android:text="Send"/></LinearLayout>

如果仅指定EditView的weight属性,将Button的width改为wrap_content,Button的宽度仍按wrap_content计算,而Editview会占据剩下的空间,这种方式编写的程序,不仅在各种屏幕上适配性很好,而且看起来也很舒服,如下图。