Does anybody know how to easily implement an action bar with two stretched buttons?
Here is an example of the Google calendar app:
Thank you!
If you rather have this in the ActionBar for whatever reason, one way to achieve this is by using a custom view on the Action bar. Within you Custom View's layout then worry about setting up the buttons width.
Telling the activity to use a custom view for the action bar:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ActionBar ab = getActionBar(); ab.setDisplayShowHomeEnabled(false); ab.setDisplayShowTitleEnabled(false); final LayoutInflater inflater = (LayoutInflater)getSystemService("layout_inflater"); View view = inflater.inflate(R.layout.action_bar_edit_mode,null); ab.setCustomView(view); ab.setDisplayShowCustomEnabled(true); }
layout/action_bar_edit_mode.xml can then look something like:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="fill_horizontal" android:orientation="horizontal" > <LinearLayout android:layout_alignParentLeft="true" android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal"> <Button android:id="@+id/action_bar_button_cancel" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_weight="1" android:text="Cancel" /> <Button android:id="@+id/action_bar_button_ok" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_weight="1" android:text="Ok" /> </LinearLayout> </RelativeLayout>
Hope it helps someone!
Note: I realize the ugly nesting layouts here and normally I wouldn't recommend this but for some reason the actionbar's own layout refuses to let the LinearLayout take up the entire width on its own. Normally you should avoid nesting layouts unnecessarily like this! Perhaps if someone sees this they can point us to a better solution?
What it looks like:
EDIT: There is an excellent post by Roman Nurik where he explains a way to do this very nicely.
EDIT 2: If anyone is curious, the correct way to lay out the buttons so that they expand the width of the actionbar without the need to nest your layouts like I did above, is to set the custom view with the proper layout parameters that allows its component to match the parent group.
Essentially:
actionBar.setCustomView(view,new ActionBar.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With