Help us understand the problem. What is going on with this article?

Androidのoptions menuまわりのtips

More than 5 years have passed since last update.
  • ActionBarメニューの表示/非表示を切り替える
  • Fragmentにメニューを表示させる

ActionBarメニューの表示/非表示を切り替える

概要

ActionBarActivityなActivityのActionBarにあるメニュー(options menu)について、

MenuItem item = menu.findItem(R.id.menu_id);
item.setVisible(false);

をしても消えてくれなかったoptions menuを何とかして消す

やり方

Activity
// 初期状態ではmenuを表示させる
private boolean menuVisible = true;
private MenuItem menuToggleVisible;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_activity, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menuToggleVisible = menu.findItem(R.id.menu_toggle_visible);
    menuToggleVisible.setVisible(menuVisible);
    return true;
}

private void toggleMenuVisible() {
    menuVisible != menuVisible;
    invalidateOptionsMenu();
}

このようにonPrepareOptionsMenuの中でsetVisibleを呼び出せるようにしておく
そして、invalidateOptionsMenu()によって内部でonPrepareOptionsMenuがcallされ、
menuの表示/非表示が切り替えられる

参考

Fragmentにメニューを表示させる

Activityの上に乗せたFragmentごとにmenuを表示させたい

やり方

Fragment
private MenuItem menuItem;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    // ...
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
    super.onCreateOptionsMenu(menu, menuInflater);
    // menu.add(groupId, itemId, order, title);
    menuItem = menu.add(Menu.NONE, 0, 100, getString(R.string.menu_item));
    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}

まずonCreatesetHasOptionsMenu(true)をcallしておく
そして、onCreateOptionsMenuでoptions menuを作成する
ここではJavaだけでmenuを作成している

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした