Android - 使用TabLayout的不同菜单项

时间:2015-12-24 08:19:17

标签: android menuitem android-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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

在Android 3.0及上拨打invalidateOptionsMenu()会致电onPrepareOptionsMenu()Menu传递给该方法,您希望使用该对象对菜单进行更改,无论是添加还是删除菜单项。

请牢记onPrepareOptionsMenu()

  

您必须返回true才能显示菜单;如果你返回false,它将不会显示。

Thanks to this