Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Switch widget to ActionBar and respond to change event

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.

like image 560
Sumit Sahoo Avatar asked Apr 07 '14 17:04

Sumit Sahoo


1 Answers

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);
}
like image 177
adneal Avatar answered Oct 24 '22 09:10

adneal