Pages Navigation Menu

Coding is much easier than you think

Problems understanding Android XML layout_weight

Posted by on Apr 14, 2013 in Android | 0 comments

Weight attribute in android for your views determines how long it is stretched within the layout of an activity. The weight attribute can be best understood in case of linear layout (Orientation – Vertical)

Consider the following examples, where weight is added to 2 buttons and each time the views are arranged in different fashion for the same value of weights.

weight_layout

In the above example let’s see each case one by one.

Figure 1:

  • Button 1 is not given any weight.
  • Button 2 (wrap content) is given a weight of 1.

So the button 1 occupies normal space and button 2 occupies the remaining space of the layout.

 

  

 

Figure 2:

  • Button 1 is given a weight of 1. (33.33%)
  • Button 2 (wrap content) is given a weight of 2.  (66.66%)

So the button 1 occupies 1/3rd space and button 2 occupies the remaining space (2/3rd) of the layout.
 
** UPDATE: Android Complete tutorial now available here.
 

    

 

Figure 3:

  • Button 1 is given a weight of 1. (50%)
  • Button 2 (wrap content) is given a weight of 1.  (50%)

So the button 1 occupies first half and button 2 occupies the remaining half of the layout.

 

Thus weight can be used effectively in a layout to arrange your views.

Read More