Android应用UI开发,对以上布局,可以使用RelativeLayout, 即:
<RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical"> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="search"/> <EditText android:id="@+id/edit1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toLeftOf="@id/btn1" android:hint="input the key word"/> </RelativeLayout>
也可以使用LinearLayout的 layout_weight属性,即
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="input the key word" android:layout_weight="1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="search"/> </LinearLayout>
再多说几句layout_weight, Android SDK document中对layout_weight有如下解释:
Specifies how much of the extra space in the layout to be allocated to the View.
LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Default weight is zero
calculation to assign any remaining space between child
space assign to child = (child individual weight) / (sum of weight of every child in Linear Layout)
Example (1): if there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then remaining space assign to
1st text box = 1/(1+1+0) 2nd text box = 1/(1+1+0) 3rd text box = 0/(1+1+0)
Example (2) : let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important).
calculation : 1st label = 0/(0+1+1) 2nd text box = 1/(0+1+1) 3rd text box = 1/(0+1+1)
If the first one text box has a layout_weight of 1 and the second text box has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).
calculation : 1st label = 0/(0+1+2) 2nd text box = 1/(0+1+2) 3rd text box = 2/(0+1+2)
值得注意的是, layout_weight是对LinearLayout里剩余或多余的空间再分配给指定layout_weight的view元素。因此,在对每个view元素的layout_width或layout_height写不同的值是可能有不同的结果的。 对本文最上面的图表示的一个文本编辑框和一个按钮,只有两个view元素, 文本框的layout_weight=1,而layout_width写fill_parent或wrap_content都是一样的。但若有两个文本框和一个按钮同在一行,这两个文本框的layout_weight一个为1,一个为2,想要的效果是一个文本框的长度是另一个的2倍,要达到此效果,两文本框的layout_width须设为0dip, 这样由layout_weight要控制每个文本框的宽度分配。