Add Switch widget to ActionBar and respond to change event
Asked Answered
L

2

8

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 to change event. I have added below to main.xml.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.MainActivity" >

    <item
        android:id="@+id/toggleservice"
        android:actionViewClass="android.widget.Switch"
        android:showAsAction="ifRoom"
        android:title="@string/toggle_service"/>

</menu>

I want to start a service when user clicks on switch and change it's state. Any help is highly appreciated.

Likeminded answered 7/4, 2014 at 17:9 Comment(0)
C
18

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);
}
Coven answered 7/4, 2014 at 18:20 Comment(4)
Awesome, searched everywhere but was unable to find any solution. You just saved my day. Thanks a ton :)Likeminded
Same here, where did you find this? any book or recomended lecture?Lubalubba
@demil133 Just the docsCoven
Note that: xml file should only contain "switsh"Palpable
G
0

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.
}
Grof answered 10/12, 2014 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.