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
For those of you using Xamarin. This is the translated version of adneal's answer:
private Switch _actionViewSwitch;
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.main_activity_actions, menu);
var menuItem = menu.FindItem(Resource.Id.toggleservice);
_actionViewSwitch = (Switch) menuItem.ActionView;
_actionViewSwitch.CheckedChange += ActionViewOnCheckedChange;
return base.OnCreateOptionsMenu(menu);
}
private void ActionViewOnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs checkedChangeEventArgs)
{
// ToDo: stuff that happens when switch gets checked.
}
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);
}