这是我的问题:
我有一个activity
toolbar
和view pager
,其中包含三个主fragments
,其中两个嵌套fragments
:
在ListFragment
我创建了一个菜单,其中包含用于过滤recycler view
的搜索按钮,该按钮已在fragment
中实现。在我的整个应用程序中,我只在ListFragment
中初始化了一个按钮。 Search button
工作正常,但在[1]和[3]标签上也可见。有没有办法从这些标签中隐藏它?我试图在setHasOptionsMenu(true)
中设置onPrepareOptionsMenu
和menu.getItem(R.id.action_search).setVisible(false)
来实现invalidateOptionsMenu()
和fragments
,但不需要此菜单项,但它没有用。任何想法如何实现?这是我的代码:
RootListFragment
public class RootListFragment extends Fragment {
private FragmentManager fragmentManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_root_list, container, false);
fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().add(R.id.root_list_fragment, new ListFragment()).commit();
return view;
}
}
ListFragment
public class ListFragment extends Fragment implements SearchView.OnQueryTextListener {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
...
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
});
}
}
GraphFragment
public class GraphFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_graph, container, false);
...
return view;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.getItem(R.id.action_search).setVisible(false);
super.onPrepareOptionsMenu(menu);
}
}
这是我的应用程序中的gif:
答案 0 :(得分:0)
在您不想显示任何菜单选项的Fragment
中,setHasOptionsMenu(false);
中需要onCreate()
,如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}