0

I get null pointer when I try to refer the actionView in drawer menu item. I need to refer view nl.dionsegijn.steppertouch.StepperTouch (defined in locaton_item_layout.xml) in my MainActivity.java file. I'm trying to run following code to do so. Now, the value returned for variable actionViewLayout is null. I'm not sure what I'm missing here. Please help.

Here's my MainActivity.java file:

...
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_drawer, menu);
        LinearLayout actionViewLayout = (LinearLayout) menu.findItem(R.id.item_with_action).getActionView();
        stepperTouch = (StepperTouch) actionViewLayout.findViewById(R.id.stepperTouch);
        return super.onCreateOptionsMenu(menu);
    }
...

Here's activity_main_drawer.xml file:

...
    <item
        android:id="@+id/item_with_action"
        android:title="Show Results for"
        app:actionLayout="@layout/location_item_layout">
        app:showAsAction="always"
    </item>
...

Here's location_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:id="@+id/actionviewlayout">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Now+"
    android:textSize="30sp"/>
    <nl.dionsegijn.steppertouch.StepperTouch
        android:id="@+id/stepperTouch"
        android:layout_width="100dp"
        android:layout_height="40dp">
    </nl.dionsegijn.steppertouch.StepperTouch>
</LinearLayout>
Jay Bhavsar
  • 159
  • 1
  • 14

1 Answers1

0

You need to access the menu item in onPrepareOptionsMenu(). You should only initialize the menu in onCreateOptionsMenu(). From the documentation:

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

So, you need to move your code to onPerepareOptionsMenu():

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  LinearLayout actionViewLayout = (LinearLayout) menu.findItem(R.id.item_with_action).getActionView();
  stepperTouch = (StepperTouch) actionViewLayout.findViewById(R.id.stepperTouch);

  return super.onPrepareOptionsMenu(menu);
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96