North Border Software

Home Tutorials Hints & Tips About

Android Apps and Training

Share on Facebook Share on Twitter

Getting Started in Android Development

Part 16 - WeightSum and Weight

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.

Android Layout without WeightSum and Weight

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:

Android Layout with WeightSum and Weight

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.

Android Layout with WeightSum and Weight

After this tutorial your should look different to the one below:

Your should look similar to the one below:

And your Android manifest file should look similar to the one below:

Download tutorial set 1

© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo