问题描述
一个Android应用具有以下代码:
An Android app has the following code:
public class FooActivity extends AppCompatActivity{
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
}
}
单击三点溢出菜单按钮时,菜单将正常显示,并调用此MenuOpened(int featureId,Menu menu),但菜单为null.这正常吗?
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?
推荐答案
单击菜单图标onMenuOpened
会被调用两次:第一次立即调用,然后在准备菜单时调用.显然,第一次它为空是因为它没有准备好.因此,如果您想访问此回调中的菜单-只需将其检查为null即可;否则请执行其他操作.
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.
简单的实验:
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);
}
}
单击菜单图标时输出:
D/tag: onMenuOpened called
D/tag: menu is null yet
D/tag: onPrepareOptionsMenu called
D/tag: onMenuOpened called
D/tag: menu is ready
这篇关于为什么AppCompatActivity.onMenuOpened(int featureId,Menu menu)的菜单为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!