最佳答案
我使用菜单抽屉,它有更多的 Fragment
。在一些 Fragment
中我有菜单项 REFRESH,但是在一些片段中我想隐藏这个菜单项(我不想显示菜单,但是我不想隐藏 ActionBar
)。
我尝试添加覆盖 onCreateOptionsMenu()
到 Fragment
,我不想显示这个菜单项,但我不能让它工作。我尝试用多种方式查看代码中的注释行。知道问题出在哪里吗?最后这个菜单项去隐藏当我激活菜单抽屉时,被称为 onPrepareOptionsMenu()
在主要活动,但我需要做到这一点,当我在 Fragment
。
返回文章页面隐藏菜单项译者:
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
//setHasOptionsMenu(false);
return rootView;
}
private Menu menu=null;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.main, menu);
this.menu=menu;
menu.findItem(R.id.refresh).setVisible(false);
getActivity().invalidateOptionsMenu();
//setHasOptionsMenu(false);
super.onCreateOptionsMenu(menu,inflater);
}
}
主要活动定义菜单抽屉:
//Slide menu item click listener
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.refresh:
Toast.makeText(this, "Refreshing data...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// Called when invalidateOptionsMenu() is triggered
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.refresh).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}