I found this post How to add a switch to android action bar? and this works for me. But I can't get its event. I'm using appcompat, and I used app namespace for actionLayout and showAsAction, but I'm not able to handle its click on onOptionsItemSelected method?. My app is crashing on start up. how to handle it or what is wrong with this code? here is my code
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_layout"/>
switch_layout.xml
<?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" >
<Switch
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />
</RelativeLayout>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem menuItem= menu.findItem(R.id.myswitch);
Switch switcha = (Switch)menuItem.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}
and
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.myswitch) {
//do something
}
return super.onOptionsItemSelected(item);
}
Any help is highly appreciated. Thanks in advance.
I found my error. I have to use
View view = MenuItemCompat.getActionView(menuItem);
extra line in onCreateOptionsMenu to find out the switch button . Here is my full method
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.myswitch);
View view = MenuItemCompat.getActionView(menuItem);
Switch switcha = (Switch) view.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With