用ViewPager.OnPageChangeListener + 重写 FragmentPagerAdapter 中的 instantiateItem 方法保存Fragment的tag。
具体实现:
public class ActListFragmentAdapter extends TabFragmentAdapter {
private FragmentManager mFragmentManager;
private SparseArray mFragmentTags;
public ComboListFragmentAdapter(@NonNull FragmentManager fm, @NonNull List titles, @NonNull List fragments) {
super(fm, titles, fragments);
mFragmentManager = fm;
mFragmentTags = new SparseArray<>();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
mFragmentTags.append(position, tag);
}
return object;
}
public Fragment getFragment(int position){
String tag = mFragmentTags.get(position);
if(StringUtil.isStringEmpty(tag)){
return null;
}
return mFragmentManager.findFragmentByTag(tag);
}
}
然后在pager切换的监听中判断符合条件的回调onResume
mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Fragment currentFragment = mTabFragmentAdapter.getFragment(position);
if ((0 == position || position == mTabFragmentAdapter.getCount() - 1) && null != currentFragment) {
currentFragment.onResume();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});