Getting the current Fragment instance in the viewpager

前端 未结 30 2487
醉话见心
醉话见心 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:15

    by selecting an option, I need to update the fragment that is currently visible.

    A simple way of doing this is using a trick related to the FragmentPagerAdapter implementation:

    case R.id.addText:
         Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());
         // based on the current position you can then cast the page to the correct 
         // class and call the method:
         if (ViewPager.getCurrentItem() == 0 && page != null) {
              ((FragmentClass1)page).updateList("new item");     
         } 
    return true;
    

    Please rethink your variable naming convention, using as the variable name the name of the class is very confusing(so no ViewPager ViewPager, use ViewPager mPager for example).

提交回复
热议问题