Rishabh Rishabh -4 years ago 114
Android Question

How to add switch listener in action bar android?

I am trying to add a listener to my switch in action bar for that I have read a lot of answers about it on StackOverflow but my app is crashing on below point.

my main menu xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_layout"/>
</menu>


my switch layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</RelativeLayout>


My on create options menu is this

@Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.mainmenu, menu);
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.getItemId() == R.id.myswitch) {
View view = MenuItemCompat.getActionView(item);
if (view != null) {
**Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar);**
//to do add a listener for this switch
}
}
}

return true;
}


On debugging constantly I found that Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar); this line results in application crash. I hope my problem is clear now. I want to attach a listener to my action bar switch but I am unable to get an instance to the object of that switch. Above is how most of the answers on StackOverflow have directed to do. Any help on this would be highly appreciated.

Thank you

Answer Source
Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar);

Should be

SwitchCompat mainSwitchOnOffSw = (SwitchCompat) view.findViewById(R.id.switchForActionBar);

as you are using SwitchCompat in your layout.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download