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
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);
}