Home » Android » android – How to add actions to the top part of a split ActionBar

android – How to add actions to the top part of a split ActionBar

Posted by: admin May 14, 2020 Leave a comment

Questions:

If an Android ActionBar is split into a top and a bottom portion using android:uiOptions="splitActionBarWhenNarrow" in the Manifext.xml,
is there a way to force some of the actions to be displayed in the top portion instead of having them all at the bottom?

How to&Answers:

There’s no standard way of doing this. That said, the Action Bar custom view will appear in the upper bar, so you can just use that. You will lose some of the extras (toasts on long press), so you’ll have to implement them yourself. That said, of you’re using ActionBarSherlock, all the layouts and styles for a normal button are there, so you can just use those.

Answer:

Yes! You can continue to use android:uiOptions="splitActionBarWhenNarrow" in your Manifest.xml.

You just also need to set:

// set the actionbar to use the custom view
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

//set the custom view to use
getActionBar().setCustomView(R.layout.custom_action_bar_top);

Where R.layout.custom_action_bar_top would be a view that has all the buttons you wish to appear in the top action bar.

All the menu items that you want at the bottom, should be added as usual in the onCreateOptionsMenu method of your activity.

Answer:

I would like to second Dylan Watson’s solution, but with one improvement.
For those who would like to keep the title, and not replace the entire actionBar with their new View, they use getActionBar().setDisplayShowCustomEnabled(true) , rather than getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); , as the latter will cause the new view to be the only view displayed in the actionbar. My code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = new SearchView(this);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    getActionBar().setDisplayShowCustomEnabled(true);
    getActionBar().setCustomView(searchView, new ActionBar.LayoutParams(Gravity.RIGHT));
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}