Add toggle button to the menu to stop and start service

后端 未结 6 825
抹茶落季
抹茶落季 2020-12-11 03:24

I am trying to enable the user to stops and starts service which I am implementing from the Menu where the text is will be changed when he clicks it so I want to add T

6条回答
  •  臣服心动
    2020-12-11 03:55

    As mentioned above, you can't add toggle button to the menu. You can use the android:checkable property in your menu item to handle the two states.

    Something like:

    Menu:

    
    

    Activity:

    private boolean isChecked = false;
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem checkable = menu.findItem(R.id.checkable_menu);
        checkable.setChecked(isChecked);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.checkable_menu:
                isChecked = !item.isChecked();
                item.setChecked(isChecked);
                return true;
            default:
                return false;
        }
    }
    

    PS: Copied the code from here.

    Or you can just update your item icon on click event to show the two states with item.setIcon(yourDrawable));

提交回复
热议问题