Why getActionView () returns null

I have been looking for a solution for this for several hours. I just want to add a switch under the ActionBar (as in the Bluetooth settings). I found a similar question here, but it was probably old. Anyways here is my code:

MainActivity:

@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); MenuItem item = menu.findItem(R.id.myswitch); switchButton = (Switch) item.getActionView(); return super.onCreateOptionsMenu(menu); } 

menu_main.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" > <item android:id="@+id/menu_switch" android:title="off/on" app:showAsAction="always" app:actionLayout="@layout/switchlayout" app:actionViewClass="android.support.v7.widget.Switch" /> </menu> 

switchlayout.xml

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal"> <Switch android:id="@+id/myswitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:background="#1E88E5" /> </RelativeLayout> 

But no matter what I do, I always get:

Trying invoke ... getActionView () 'to reference a null object

I am confused because I just defined the element, before R.id.myswitch is R.id.myswitch , did I R.id.myswitch it up?

+5
source share
3 answers

In addition to a simple erroneous type (it should be menu_switch match your XML), in accordance with the training of actions , you need to use MenuItemCompat.getActionView () to extract the ActionView (and, in your case, apply it to SwitchCompat , since there is no android.support.v7.widget.Switch ).

 @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); MenuItem item = menu.findItem(R.id.menu_switch); switchButton = (SwitchCompat) MenuItemCompat.getActionView(item); return super.onCreateOptionsMenu(menu); } 
+4
source

Replace

 MenuItem item = menu.findItem(R.id.myswitch); 

with

 MenuItem item = menu.findItem(R.id.menu_switch); 

Avoid having your item id in the xml menu be menu_switch, not myswitch.

+3
source

How about using MenuItemCompat with a static function:

 MenuItemCompat.getActionView (MenuItem item) 
+2
source

Source: https://habr.com/ru/post/1235266/


All Articles