Swipe view with different actionbar items in each swipe fragment

后端 未结 1 999
生来不讨喜
生来不讨喜 2021-01-20 22:58

I want to change the actionbar items on each swipe fragment. Actually I want submit button on actionbar for only third swipe fragment. For example I have 3 fragment in swipe \"a

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 23:47

    In your viewpager container (Activity or Fragment), add the next line in your page change listener:

    invalidateOptionsMenu();
    supportInvalidateOptionsMenu();//if using the actionbar support library
    getActivity().invalidateOptionsMenu();//if your viewpager container is a fragment
    

    it would be something like this:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        yourViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                invalidateOptionsMenu();
            }
        });
    }
    

    Then create your onCreateOptionsMenu(). The menu layout is going to have all the different icons you want to show:

        @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.your_menu_layout, menu);
    
    }
    

    The onPrepareOptionsMenu() callback method is called before the menu is shown, and we are going to use it to make the menu items visible depending on the current fragment:

        @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        int page = yourViewPager.getCurrentItem();
        switch(page) {
            case 0:
                menu.findItem(R.id.item_f1).setVisible(true);
                menu.findItem(R.id.item_f2).setVisible(false);
                menu.findItem(R.id.item_f3).setVisible(false);
                break;
            case 1:
                menu.findItem(R.id.item_f1).setVisible(false);
                menu.findItem(R.id.item_f2).setVisible(true);
                menu.findItem(R.id.item_f3).setVisible(false);
                break;
            case 2:
                menu.findItem(R.id.item_f1).setVisible(false);
                menu.findItem(R.id.item_f2).setVisible(false);
                menu.findItem(R.id.item_f3).setVisible(true);
                break;  
        }
        return true;
    }
    

    and that's it.

    If your viewpager container is a fragment, add setHasOptionsMenu(true), if it is an activity is not necessary.

    0 讨论(0)
提交回复
热议问题