How can i set a tag for viewpager fragments?

前端 未结 3 1224
再見小時候
再見小時候 2020-12-31 01:41

I,m using slidingTabLayout with 4 tabs and a viewpager and 4 fragment class for every tab.

i need to reload one of my fragments (first tab) in my project when user

3条回答
  •  攒了一身酷
    2020-12-31 02:25

    There are couple of solution for this.

    1). When the FragmentPagerAdapter adds a Fragment to the FragmentManager, it uses a special tag based on the particular position that the Fragment will be placed. So you can simply get the current visible Fragment in your ViewPager using these lines of code

     Fragment fragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());
     // based on the current position you can then cast the page to the correct Fragment class and call some method inside that fragment to reload the data:
     if (0 == ViewPager.getCurrentItem() && null != fragment) {
          ((TabFragment1)fragment).reloadFragmentData();     
     } 
    

    2). You should keep track of all the active fragments in the FragmentStatePagerAdapter. For demo sample you can refer to second approach here

    3). You can make use of EventBus to post events to your Fragment from anywhere. All you have to do is to register your Fragment for that specific event. For official documentation refer this

提交回复
热议问题