onCreateOptionsMenu
恢复时都会调用 Fragment
。创建片段后,是否有解决方案可仅调用onCreateOptionsMenu
once
?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint(getString(R.string.search_hint));
searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
showContacts();
return true;
}
});
}
答案 0 :(得分:1)
它已连接到生命周期,因此将调用该方法。这并不意味着您的代码需要每次都被调用。设置一个类级别的布尔值以确保代码仅运行一次。或检查'getOnActionExpandListener'...
if(searchItem.getOnActionExpandListener() == null) {
searchItem.setOnActionExpandListener.......
}