Android - 使用 TabLayout 的不同菜单项

Android - Different menu items with TabLayout

我的应用程序中有一个 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;
    }
}

您需要使用 invalidateOptionsMenu()onPrepareOptionsMenu()。您应该阅读文档。

仔细看看这个:http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu

在 Android 3.0+ 上调用 invalidateOptionsMenu() 将调用 onPrepareOptionsMenu()Menu 被传递给该方法,您希望使用该对象对菜单进行更改,无论是添加还是删除菜单项。

请记住 onPrepareOptionsMenu()

You must return true for the menu to be displayed; if you return false it will not be shown.

Thanks to this