划重点:
1、更该继承 FragmentPagerAdapter 为 FragmentStatePagerAdapter;
2、在修改adapter数据之前进行清空fragment 缓存数据
以下是完整类代码
import android.util.SparseArray;
import android.widget.FrameLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class BaseFragmentPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
private String[] mTitles;
private FragmentManager fm;
public BaseFragmentPagerAdapter(FragmentManager fm, List<Fragment> mFragments, String[] mTitles) {
super(fm);
this.fm = fm;
this.mFragments = mFragments;
this.mTitles = mTitles;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments != null ? mFragments.size() : 0;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles != null || mTitles.length > position ? mTitles[position] : "";
}
/**
* 方法一,这种方式可以移除所有fragment缓存
**/
public void removeAllFragment() {
for (int i = mFragments.size() - 1; i >= 0; i--) {
Fragment fragment = mFragments.get(i);
//然后从List中移除
mFragments.remove(fragment);
//先从Transaction移除
removeFragmentInternal(fragment);
}
//最后刷新Adapter
notifyDataSetChanged();
}
/**
* 从Transaction移除Fragment
* @param fragment 目标Fragment
*/
private void removeFragmentInternal(Fragment fragment) {
FragmentTransaction transaction = fm.beginTransaction();
transaction.remove(fragment);
transaction.commitNow();
}
// 方法二
public void clearAll(){
//先保证ViewPager之前已设置过Adapter,这样才有可能存在缓存
// if (mContentVp.getAdapter() != null) {
//获取FragmentManager实现类的class对象,这里指的就是FragmentManagerImpl
Class<? extends FragmentManager> aClass = fm.getClass();
try {
//1.获取其mAdded字段
Field f = aClass.getDeclaredField("mAdded");
f.setAccessible(true);
//强转成ArrayList
ArrayList<Fragment> list = (ArrayList) f.get(fm);
//清空缓存
list.clear();
//2.获取mActive字段
f = aClass.getDeclaredField("mActive");
f.setAccessible(true);
//强转成SparseArray
SparseArray<Fragment> array = (SparseArray) f.get(fm);
//清空缓存
array.clear();
} catch (Exception e) {
e.printStackTrace();
}
// }
//再次设置ViewPager的Adapter
// mContentVp.setAdapter(new PageAdapter(getChildFragmentManager()));
}
}
网友评论