I have a switch within a menu that is show as an action on the action bar. The onCheckedChangeListener is not being invoked immediately after when I set the checked property to true. The switch does show up in the action bar, and every time it is pressed it the checkedchangelistener is invoked. However, it is not invoked in the beginning when it should be. How is this possible? Why is it not invoked? How do I fix this?
Here is the onCreateMenuOptionsMenu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu()");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
serviceSwitch = (Switch) menu.findItem(R.id.Switch).getActionView().findViewById(R.id.switchid);
serviceSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
serviceSwitch.setChecked(false);
//OnCheckedChange is not being called here. I have set a breakpoint at the method.
//I have also looked at the log - nothing.
//It is being called when I click the switch however.
return true;
}
private OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, isChecked ? "true" : "false";
}
}
Here is the xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title=""
android:id="@+id/Switch"
android:actionLayout="@layout/switch_layout"
android:showAsAction="always"></item>
</menu>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Switch
android:id="@+id/switchid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:textOff="Off"
android:textOn="On"
android:checked="true"/>
</RelativeLayout>
R.layout.switch_layout
Switch checked value is already true in your layout file.
android:checked="true"
so when set its value to true its checked change listener is not called.
Hope you get my point.