Getting Started in Android Development
Part 16 -
The child views in a linear layout are normally arranged in a row or column depending on their orientation. The screen shot below shows an example where four horizontally orientated buttons are set with a width attribute of wrap_content.
You can see that button B4 does not have enough space available on the screen to show its full width and it appears squashed relative to the other buttons.
The android XML weightsum and weight attributes provide the developer with a means to control the proportion of the screen that a view will use.
In the example below the XML weightsum attribute is added to the parent layout. It is given a value of five. Each of the layout children, the four buttons, is given an XML weight attribute. The first button B1 is given a weight of 2 such that it occupies 2/5 of the screen width. The others, with a weight of 1, occupy 1/5 of the screen each. The other thing to note that is that each button has a width attribute of 0dp, the width being controlled by the weight.
The resultant screenshot is below:
It is worth noting that the sum of the weights, does not have to equal the weightsum. In the example above, if the first button is given the weight of one, then it will occupy 1/5 of the screen and all four buttons will occupy 4/5 of the screen with a 1/5 gap after the forth button.
After this tutorial your WeightSumActivity.java should look different to the one below:
Your ListviewActivity.java should look similar to the one below:
And your Android manifest file should look similar to the one below: