Android应用程序具有以下代码:
public class FooActivity extends AppCompatActivity{ @Override public boolean onMenuOpened(int featureId, Menu menu) { } }
单击3点溢出菜单按钮时,菜单会正常显示,并调用此MenuOpened(int featureId,菜单菜单),但菜单为空.这是正常的吗?
当您单击菜单图标时,onMenuOpened
会调用两次:第一次立即,然后准备菜单时.显然第一次它是null因为它没有准备好.因此,如果您想要在此回调中访问菜单 - 只需将其检查为null,如果不是则执行操作.
简单实验:
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