【问题标题】:How to remove MenuItems from Menu programmatically?如何以编程方式从菜单中删除 MenuItems?
【发布时间】:2012-10-15 11:35:53
【问题描述】:

我正在开发一些 Android 应用程序,并且我有一些菜单代码:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:showAsAction="ifRoom"
        android:id="@+id/menuItemToLeft"
        android:icon="@drawable/to_left" />
    <item
        android:showAsAction="ifRoom"
        android:id="@+id/menuItemToRight"
        android:icon="@drawable/to_right"/>
</menu>

我使用“showAsAction”来在操作栏上显示这些项目。此外,我还有 3 个用于导航的选项卡。 But there is the following task: remove (or set visibility as false) this items from Action bar when tab with 0 positions is selected.但我不明白我该怎么做:

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());
    if (tab.getPosition()==0) {
    //some code
    }
}

【问题讨论】:

    标签: java android


    【解决方案1】:

    尽量不要使用:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.menuItemToLeft).setVisible(true);
        menu.findItem(R.id.menuItemToRight).setVisible(false);
        return true;
    }
    //true or false depending on your requirements
    

    或删除:

    menu.removeItem(x); //where x is the number of the menu item from 0,1,...
    

    然后您可能需要使用 menu.Add() 再次创建 MenuItem

    【讨论】:

    • onPrepareOptionsMenu 仅调用 1 次,而不是每次更改选项卡时调用。
    • 你是对的,但用户应该调用“invalidateOptionsMenu”才能再次执行“onPrepareOptionsMenu”
    • @Stephen Walker 如果您将马尔科里的观点添加到您的答案中,它将变得更加易于阅读。
    【解决方案2】:

    一个非常小的解决方案:

    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {
    Menu myMenu;
    
    
    protected void onCreate(Bundle savedInstanceState) {
    .....
    }
    
       @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            myMenu = menu;
            return true;
        }
    
     @Override
        public boolean onNavigationItemSelected(MenuItem item) {
    
    int id = item.getItemId();
    if (id == R.id.feedsenglish)
            {
                myMenu.findItem(R.id.allfeeds).setVisible(false);
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      相关资源
      最近更新 更多