1、pager.setOffscreenPageLimit(fragmentList.size());避免fragment销毁,重复创建
2、定义抽象类
- 将Fragment加载数据的逻辑放到onResume()方法中,这样就保证了Fragment可见时才会加载数据。
- 声明一个变量标记是否是首次执行onResume()方法,因为每次Fragment由不可见变为可见都会执行onResume()方法,需要防止数据的重复加载。
public abstract class LazyViewPager2Fragment extends Fragment implements View.OnClickListener{
public static final String TAG = "LazyFragment";
View rootView;
private boolean isFirstLoad = true; // 是否第一次加载
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.i(TAG,"onCreateView");
if(rootView == null){
rootView = inflater.inflate(getLayoutId(),container,false);
}
initView(rootView);
return rootView;
}
/**
* 布局id
* @return
*/
protected abstract int getLayoutId();
/**
* 初始化控件
* @param rootView
*/
protected abstract void initView(View rootView);
//数据加载
public void onDataLoad(){
Log.i(TAG,"onDataLoad");
}
//停止加载数据
public void onDataLoadStop(){
Log.i(TAG,"onDataLoadStop");
}
@Override
public void onResume() {
super.onResume();
Log.i(TAG,"onResume");
if(isFirstLoad){
onDataLoad();
isFirstLoad = false;
}
}
}