I am trying to add a Switch widget to my ActionBar , but when I try to implement it, it does not appear or, if so, my ActionBart title disappears. I have done the following:
I created a Layout for this Switch
?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.support.v7.widget.SwitchCompat android:id="@+id/switchAB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout>
And then on my menu_main.xml I added the following:
<item android:id="@+id/switchId" android:title="" app:showAsAction="ifRoom" android:actionLayout="@layout/swipe_wifi" />
I changed android to app because the tooltip says that

Then in my ActivityMain onCreateOptionsMenu() if you add this to do a quick test
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); switchAB = (Switch)menu.findItem(R.id.switchId) .getActionView().findViewById(R.id.switchAB); switchAB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Toast.makeText(getApplication(), "ON", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(getApplication(), "OFF", Toast.LENGTH_SHORT) .show(); } } }); return true; }
But it gives me a NPE in this strip
switchAB = (Switch)menu.findItem(R.id.switchId)
Can I change something in my code?
android
Skizo-ozα΄ΚS Jun 27 '15 at 13:09 on 2015-06-27 13:09
source share