Getting the current Fragment instance in the viewpager

前端 未结 30 1926
醉话见心
醉话见心 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 09:19

    This is the only way I don't get NullPointerException for the instance variables of that particular fragment classes. This might be helpful for others who stuck at the same thing. In the onOptionsItemSelected(), I coded the below way:

    if(viewPager.getCurrentItem() == 0) {
        FragmentClass1 frag1 = (FragmentClass1)viewPager
                                .getAdapter()
                                .instantiateItem(viewPager, viewPager.getCurrentItem());
        frag1.updateList(text); 
    } else if(viewPager.getCurrentItem() == 1) {
        FragmentClass2 frag2 = (FragRecentApps)viewPager
                                .getAdapter()
                                .instantiateItem(viewPager, viewPager.getCurrentItem());
        frag2.updateList(text);
    }
    

提交回复
热议问题