Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is menu of AppCompatActivity.onMenuOpened(int featureId, Menu menu) null?

An Android app has the following code:

public class FooActivity extends AppCompatActivity{
   @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
    }
}

When the 3-dot overflow menu button is clicked, the menu is displayed normally, and this MenuOpened(int featureId, Menu menu) is called, but menu is null. Is this normal?

like image 475
Hong Avatar asked Jan 09 '17 23:01

Hong


1 Answers

When you click the menu icon onMenuOpened is called twice: first time immediately, then when menu is prepared. Obviously first time it is null because it is not prepared. So if you want to access menu in this callback - just check it for null and do things if it's not.

Simple experiment:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("first");
        menu.add("second");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Log.d("tag", "onPrepareOptionsMenu called");
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        Log.d("tag", "onMenuOpened called");
        if(menu!=null) {
            Log.d("tag", "menu is ready");
        } else {
            Log.d("tag", "menu is null yet");
        }
        return super.onMenuOpened(featureId, menu);
    }
}

Output when menu icon clicked:

D/tag: onMenuOpened called
D/tag: menu is null yet
D/tag: onPrepareOptionsMenu called
D/tag: onMenuOpened called
D/tag: menu is ready
like image 164
Maksim Ostrovidov Avatar answered Oct 21 '22 10:10

Maksim Ostrovidov