How to get/set action event in Android actionbar switch

前端 未结 1 1356
刺人心
刺人心 2021-01-06 09:48

I found this post How to add a switch to android action bar? and this works for me. But I can\'t get its event. I\'m using appcompat, and I used app namespace for actionLay

相关标签:
1条回答
  • 2021-01-06 10:10

    I found my error. I have to use

    View view = MenuItemCompat.getActionView(menuItem);

    extra line in onCreateOptionsMenu to find out the switch button . Here is my full method

    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
    
            MenuItem menuItem = menu.findItem(R.id.myswitch);
            View view = MenuItemCompat.getActionView(menuItem);
            Switch switcha = (Switch) view.findViewById(R.id.switchForActionBar);
            switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // do anything here on check changed 
                }
            });
            return super.onCreateOptionsMenu(menu);
    }
    
    0 讨论(0)
提交回复
热议问题