Add Switch widget to ActionBar and respond to change event

前端 未结 2 2105
忘掉有多难
忘掉有多难 2021-02-06 09:02

Can I know how to add Switch widget in ActionBar and handle the click event or toggle change event.

For now I can inflate the Switch in ActionBar but unable to respond t

2条回答
  •  感动是毒
    2021-02-06 09:47

    You need to call MenuItem.getActionView, here's an example:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate your Menu
        getMenuInflater().inflate(R.menu.your_menu, menu);
    
        // Get the action view used in your toggleservice item
        final MenuItem toggleservice = menu.findItem(R.id.toggleservice);
        final Switch actionView = (Switch) toggleservice.getActionView();
        actionView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // Start or stop your Service
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
    

提交回复
热议问题