I always read about this funny weight value in the Android documentations. Now I want to try it for the first time but it isn't working at all.
As I understand it from the documentations this layout:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="Register"
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
weight="1" />
<Button
android:text="Not this time"
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
weight="1" />
</LinearLayout>
should create two buttons that are horizontally aligned and share the space equally. The problem is the two buttons don't grow to fill the space.
I would like the buttons to grow and fill the whole line. If both buttons are set to match parent only the first button is shown and fills the whole line.
In the width field of button, replace
wrap-content
with0dp
.Use layout_weight attribute of a view.
This is how your code will look like:
layout_weight is used to distribute the whatever left space into proportions. In this case, the two buttons are taking "0dp" width. So, the remaining space will be divided into 1:1 proportion among them, i.e. the space will be divided equally between the Button Views.
Try setting the
layout_width
of both buttons to "0dip" and theweight
of both buttons to0.5
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/Extra space between child. (not the total space)
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/Extra space assign to
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).
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).
You are not setting the
layout_weight
property. Your code readsweight="1"
and it should readandroid:layout_weight="1"
.