我在我的应用中有一个TabLayout
。我希望每个fragment
都有自己的menu items
。我怎么能这样做?这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setToolbar();
setTabLayout();
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
rootView = inflater.inflate(R.layout.main_list, container, false);
...
break;
case 2:
rootView = inflater.inflate(R.layout.activity_maps, container, false);
...
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.list);
case 1:
return getString(R.string.map);
}
return null;
}
}
答案 0 :(得分:1)
您需要使用invalidateOptionsMenu()
和onPrepareOptionsMenu()
。你应该阅读文档。
仔细看看:http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu
在Android 3.0及上拨打invalidateOptionsMenu()
会致电onPrepareOptionsMenu()
。 Menu
传递给该方法,您希望使用该对象对菜单进行更改,无论是添加还是删除菜单项。
请牢记onPrepareOptionsMenu()
:
您必须返回true才能显示菜单;如果你返回false,它将不会显示。