Getting the current Fragment instance in the viewpager

前端 未结 30 2393
醉话见心
醉话见心 2020-11-22 08:56

Below is my code which has 3 Fragment classes each embedded with each of the 3 tabs on ViewPager. I have a menu option. As shown in the onOpt

30条回答
  •  [愿得一人]
    2020-11-22 08:58

    After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.

    Instead of having to ask each FragmentClass like

    if(FragmentClass1){
       ...
    if(FragmentClass2){
       ...
    }
    

    Create your own interface, and maker your child fragments implement it, something like

    public interface MyChildFragment {
        void updateView(int position);
    }
    

    Then, you can do something like this to initiate and update your inner fragments.

    Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
    
    if (childFragment != null) {
       ((MyChildFragment) childFragment).updateView();
    }
    

    P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState of your child fragment will be null therefor

    public void onCreate(@Nullable Bundle savedInstanceState){
          super(savedInstanceState)
    }
    

    Will crash your app.

    Good luck

提交回复
热议问题