1

I have in my app one TabLayout. I want every fragment has its own menu items. How I can do this? This is my code:

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;
    }
}
IMS
  • 265
  • 4
  • 17

1 Answers1

2

You need to use invalidateOptionsMenu() and onPrepareOptionsMenu(). You should read documentation.

Take a close look at this: http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu

Calling invalidateOptionsMenu() on Android 3.0+ will call onPrepareOptionsMenu(). A Menu is passed to that method and you want to make the changes to menu using that object, whether it be adding or removing menu items.

Keep this in mind for onPrepareOptionsMenu():

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

Thanks to this

Community
  • 1
  • 1
Mann
  • 560
  • 3
  • 13