Pages Navigation Menu

Coding is much easier than you think

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.

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.

 

  <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.