Problems understanding Android XML layout_weight

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.

[box]

weight_layout
[/box]

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.

 

  <Button 
    	android:id="@+id/button2"
    	android:text="wrapcontent"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_weight="1" />

<Button 
 	android:id="@+id/button1"
    	android:text="button1"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content" 
    	/>

 

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.
 

<Button 
 	android:id="@+id/button1"
    	android:text="button1"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content" 
    	android:layout_weight="1"/>


    <Button 
    	android:id="@+id/button2"
    	android:text="wrapcontent"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_weight="2" />


 

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.

<Button 
 	android:id="@+id/button1"
    	android:text="button1"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content" 
    	android:layout_weight="1"/>

<Button 
    	android:id="@+id/button2"
    	android:text="wrapcontent"
    	android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_weight="1" />

 

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

About Gokul


I am very much interested in android and Wicket framework. A core android developer and working in android native app development and responsive web mobile design. I have also worked in wicket fame work and java web development. I will keep on updating you about android and wicket framework and answer your query.