Enable AppCompatActivity not showing

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

enter image description here

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) //NPE--> .getActionView().findViewById(R.id.switchAB); 

Can I change something in my code?

0
android
Jun 27 '15 at 13:09 on
source share
1 answer

Try also using app:actionLayout :

 <item android:id="@+id/switchId" android:title="" app:showAsAction="ifRoom" app:actionLayout="@layout/swipe_wifi" /> 

It should also be noted that you are creating the android.widget.Switch view, while your layout has android.support.v7.widget.SwitchCompat (and this is a good choice since Switch was added in API14).

+2
Jun 27 '15 at 13:56
source share



All Articles