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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With