How can I alter a MenuItem on the Options Menu on Android?

后端 未结 6 1308
耶瑟儿~
耶瑟儿~ 2020-12-08 03:59

I have an Options Menu on my Activity with an MenuItem \"Start\". When this MenuItem is selected I would like to alter the Menu so it

6条回答
  •  轮回少年
    2020-12-08 04:50

    I got the solution. You are basically deleting the MenuItem when calling removeItem() thus also deleting the reference. Using this code works.

    private boolean isStarted = false;
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
            isStarted = true;
            return true;
        case 0:
            isStarted = false;
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    
        if(isStarted) {
            menu.removeItem(1);
            menu.add(0, 0, 0, "Stop");
        } else {
            menu.removeItem(0);
            menu.add(0, 1, 0, "Start");
        }
    
        return super.onPrepareOptionsMenu(menu);
    }
    

    You have to create the MenuItem again. Thats also the reason for the false label. Actually you don't need the MenuInflater as you create the Menu via code so also no need for any menu XML file.

提交回复
热议问题