In my app, I want to show some buttons in a LinearLayout that expands over whole width of the screen. Depending on screen size and/or orientation, I would like to hide those buttons, that don't fit in the row, in some OverflowMenu, similar to the behaviour of the ActionBar. If possible, I would like to describe the buttons in a menu resource file with the ifRoom|always attributes.
I considered displaying a Toolbar from the latest AppCompat library, but that contains too many elements that I don't need and don't know how to turn off.
Is there some library or simple way to do this?
Here is an example to do what you want. Make sure your ActionMenuView XML item is wrap_content for height and width, then gravity to the right. Surround it in a LinearLayout which takes the whole width and provides background color.
Use this code to initialize the ActionMenuView (obviously you will need to change the button callbacks)
ActionMenuView actionMenuView = (ActionMenuView) findViewById(R.id.editBar);
final Context context = this;
MenuBuilder menuBuilder = new MenuBuilder(context);
menuBuilder.setCallback(new MenuBuilder.Callback() {
@Override
public boolean onMenuItemSelected(MenuBuilder menuBuilder, MenuItem menuItem) {
return onOptionsItemSelected(menuItem);
}
@Override
public void onMenuModeChange(MenuBuilder menuBuilder) {
}
});
// setup a actionMenuPresenter which will use up as much space as it can, even with width=wrap_content
ActionMenuPresenter presenter = new ActionMenuPresenter(context);
presenter.setReserveOverflow(true);
presenter.setWidthLimit(getResources().getDisplayMetrics().widthPixels, true);
presenter.setItemLimit(Integer.MAX_VALUE);
// open a menu xml into the menubuilder
getMenuInflater().inflate(R.menu.editbar, menuBuilder);
// runs presenter.initformenu(mMenu) too, setting up presenter's mmenu ref... this must be before setmenuview
menuBuilder.addMenuPresenter(presenter, this);
// runs menuview.initialize too, so menuview.mmenu = mpresenter.mmenu
actionMenuView.setPresenter(presenter);
presenter.updateMenuView(true);
For what it's worth, I had to read the support library source code for 8 hours to get this to work. The documentation is garbage.
ActionMenuView is the part of a Toolbar which specifically controls the actions and overflow part of the Toolbar. In your case, you can use an ActionMenuView alone to implement just the actions/overflow part of the Toolbar:
ActionMenuView to the appropriate place in your XML layoutmenuInflater.inflate(R.menu.your_menu, actionMenuView.getMenu()) to inflate your menu into the ActionMenuViewIf 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