Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getActionView() return null

Tags:

java

android

I've been searching for a solution for this for hours now. I just want to add a switch under the ActionBar (like in Bluetooth settings). I found a similar question on here, but it was probably old. Anyways here's 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:

Attempt to invode ... getActionView()' on a null object reference

I'm confused because i just defined item the line before R.id.myswitch is defined, did I mess that up?

like image 523
Plays2 Avatar asked Nov 05 '15 02:11

Plays2


3 Answers

In addition to the simple mistype (it should be menu_switch to match your XML), per the action view training, you have to use MenuItemCompat.getActionView() to extract the ActionView (and, in your case, cast it to SwitchCompat as 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);
}
like image 80
ianhanniballake Avatar answered Nov 18 '22 13:11

ianhanniballake


Replace

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

with

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

Beacause your item's id in menu xml is menu_switch,not myswitch.

like image 31
starkshang Avatar answered Nov 18 '22 12:11

starkshang


How about using MenuItemCompat with static function:

MenuItemCompat.getActionView (MenuItem item)
like image 2
Kingfisher Phuoc Avatar answered Nov 18 '22 13:11

Kingfisher Phuoc