接下来我们学习下LinearLayout中的另一个重要属性——android:layout_weight 。
这个属性允许我们使用比例的方式来指定控件的大小,它在手机屏幕的适配性方面可以起到非常重要
的作用。
比如我们正在编写一个消息发送界面,需要一个文本编辑框和一个发送按钮
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/input_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type something"
/>
android:id="@+id/send"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Send"
/>
这里竟然将EditText和Button的宽度都指定成了0dp,这样文本编辑框和按钮还能显示
出来吗?不用担心,由于我们使用了android:layout_weight 属性,此时控件的宽度就不
应该再由android:layout_width 来决定,这里指定成0dp是一种比较规范的写法。另外,dp
是Android中用于指定控件大小、间距等属性的单位,后面我们还会经常用到它。
然后在EditText和Button里都将android:layout_weight 属性的值指定为1,这表示EditText
和Button将在水平方向平分宽度。
我们还可以通过指定部分控件的layout_weight 值来实现更好的效果
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/input_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type something"
/>
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
这里我们仅指定了EditText的android:layout_weight 属性,并将Button的宽度改回
wrap_content 。这表示Button的宽度仍然按照wrap_content 来计算,而EditText则会占满
屏幕所有的剩余空间。