android: changing option menu items programmatically

前端 未结 12 1925
终归单人心
终归单人心 2020-12-02 09:33

Is it possible to change the option menu items programmatically? Can anyone provide me with an example please?

Also, I want to disable certain items, so that they do

12条回答
  •  死守一世寂寞
    2020-12-02 10:15

    You can do something simple like I did. Just change the text to what is needed when the menu item is touched. I needed to turn the sound off and on, plus the ability to perform an action by touching it. Here is my code:

        @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
        case R.id.audioOn:
            audioOn = !audioOn;
            if (audioOn)
                item.setTitle("Audio Off");
            else
                item.setTitle("Audio On");
            return true;
    
        case R.id.touchOn:
            touchOn = !touchOn;
            if (touchOn)
                item.setTitle("Touch Off");
            else
                item.setTitle("Touch On");
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    

    audioOn and touchOn are booleans checked in other parts of the code. Hope this helps.

提交回复
热议问题