I found this handy post to the Android developer’s group, which explained how to get the equivalent behaviour to Apple’s flexible spacer views on toolbars.
The implementation in a layout XML file looks like this:
<LinearLayout android:id="@+id/ToolBar" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <View android:layout_width="0px" android:layout_weight="1" android:visibility="invisible"/> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/homebuttonselector" android:id="@+id/HomeButton"/> <View android:layout_width="0px" android:layout_weight="1" android:visibility="invisible"/> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/nextbuttonselector" android:id="@+id/NextButton"/> <View android:layout_width="0px" android:layout_weight="1" android:visibility="invisible"/> </LinearLayout>
Note the use of the layout_weight property for the hidden views. This tells the layout code to take whatever space is leftover from the non-weighted views (the two buttons) and divide it evenly amongst all the other views set to a weight of 1. You could play with this to do other goofy layouts as well. This is much handier than using padding, or even relative layouts to achieve the same effect because it allows you to leave the calculations up to the layout code rather than you figuring out at runtime what the padding should be. Especially if you’re adding/removing views depending on context.
UPDATE:
After playing with this a little more I actually went with this solution, which makes it even easier to programmatically show/hide the buttons.
<LinearLayout android:id="@+id/ToolBar" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <RelativeLayout android:id="@+id/Button1Layout" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1"> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/button1selector" android:id="@+id/Button1" android:layout_centerHorizontal="true"/> </RelativeLayout> <RelativeLayout android:id="@+id/Button2Layout" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1"> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/button2selector" android:id="@+id/Button2" android:layout_centerHorizontal="true"/> </RelativeLayout> </LinearLayout>
With this version to show/hide buttons all you have to do is set the visibility for the layout group the button resides in to Visibility.GONE or Visibility.VISIBLE. You don’t have to worry about having the proper arrangement of empty views to the left and right of the button.




