Saturday, November 19, 2011

Layout Tip: Spacer in LinearLayout

Sometimes you want a layout where you want a spacer view that fills that pushes views to the right of it as far as they can. A common need to do something like this is when you roll your own Action Bar.
The action bar layout with the spacer view highlighted.
XML Layout


    
    
    
    
    
    
    


Explanation
When working with LinearLayout there's an option to use weights of free space rather than a set amount of space. When the layout measures its children it first sets the fixed sized children. For this layout that's everyone except the spacer view. Then it does another pass to measure the children that will fill dimensions based on their android:layout_weight parameter. Since there's only 1 view with this parameter, it fills up the remaining space.

Source Code
actionbar.xml | Project Page

2 comments:

  1. FWIW, instead of ImageView for the spacer, just use View. This will take up the least heap space and rendering CPU time. Ice Cream Sandwich has a Space widget as well, though I'm not completely certain what it adds over just a View.

    ReplyDelete
  2. I originally used regular Views for this but I found some weird memory problems with it. Maybe this is no longer an issue or never was?http://code.google.com/p/android/issues/detail?id=18001

    ReplyDelete