网上都是通过从Fragment的setUserVisibleHint()和getUserVisibleHint()方法来入手的,但是不行,当你将viewpager滑动到第三个页面的时候,这时候你在滑到第一个页面的时候,你会发现第一个页面又被重新加载了,虽然做到了延迟加载,但是没有做到只加载一次的效果,无意间找到一位大神实现懒加载的方式,是从适配器方面入手实现的懒加载,并且实验后,发现既可以实现延迟加载,也能实现只加载一次的效果。
部分代码如下
public abstract class LazyFragmentPagerAdapter extends LazyPagerAdapter<Fragment> {
private static final String TAG = "LazyFragmentPagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
public LazyFragmentPagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
@Override
public void startUpdate(ViewGroup container) {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
mCurTransaction.attach(fragment);
} else {
fragment = getItem(container, position);
if (fragment instanceof Laziable) {
mLazyItems.put(position, fragment);
} else {
mCurTransaction.add(container.getId(), fragment, name);
}
}
if (fragment != getCurrentItem()) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
final long itemId = getItemId(position);
String name = makeFragmentName(container.getId(), itemId);
if (mFragmentManager.findFragmentByTag(name) == null) {
mCurTransaction.detach((Fragment) object);
} else {
mLazyItems.remove(position);
}
}
@Override
public Fragment addLazyItem(ViewGroup container, int position) {
Fragment fragment = mLazyItems.get(position);
if (fragment == null)
return null;
final long itemId = getItemId(position);
String name = makeFragmentName(container.getId(), itemId);
if (mFragmentManager.findFragmentByTag(name) == null) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mCurTransaction.add(container.getId(), fragment, name);
mLazyItems.remove(position);
}
return fragment;
}
@Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
public long getItemId(int position) {
return position;
}
private static String makeFragmentName(int viewId, long id) {
return "android:switcher:" + viewId + ":" + id;
}
/**
* mark the fragment can be added lazily
*/
public interface Laziable {
}
}
最后记得将自己写的Fragment实现LazyFragmentPagerAdapter.Laziable接口
github地址如下:
https://github.com/liang1075963999/lanjiazai