Change options menu during runtime - invalidateOptionsMenu()

前端 未结 1 593
轻奢々
轻奢々 2020-12-09 08:48

I am creating a menu where one of the items is used the lock an object. When this item is clicked, the menu should be recreated with a button to unlock the item. I created t

相关标签:
1条回答
  • 2020-12-09 09:43

    invalidateOptionsMenu() was added to give us the ability to force onCreateOptionsMenu() to be called again. onPrepareOptionsMenu() is still called every time you call the menu.

    What you are trying to achieve above is a good example of when to use invalidateOptionsMenu() but because of backwards compatibility you will need to do both:

    if (Build.VERSION.SDK_INT >= 11) {
      invalidateOptionsMenu();
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        if (Build.VERSION.SDK_INT >= 11) {
            selectMenu(menu);
        }
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (Build.VERSION.SDK_INT < 11) {
            selectMenu(menu);
        }
        return true;
    }
    
    private void selectMenu(Menu menu) {
        menu.clear();
        MenuInflater inflater = getMenuInflater();
    
        if (locked) {
            inflater.inflate(R.menu.changing_menu2, menu);
        }
        else {
            inflater.inflate(R.menu.changing_menu1, menu);
        }
    }
    
    0 讨论(0)
提交回复
热议问题