viewpager通常和fragment配合使用,通过viewpager的滑动操作来是实现fragment的显示和隐藏.很多的场景中,我们都希望可以实现只有在viewpager滑动到当前fragment,也就是当前fragment可见时才去加载数据,渲染view,也就是fragment的懒加载.这可以在一定程度上提高性能.
主要代码如下:
public class LazyLoadFragment extends Fragment {
private static final long TIME_DELAY = 300;
private boolean mIsVisibleToUser;
private boolean mIsViewCreated;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_LOAD_DATA:
//加载数据逻辑
break;
}
}
};
private boolean mHasLoadData = false;
public static final int MSG_LOAD_DATA = 1;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.mIsVisibleToUser = isVisibleToUser;
if(isVisibleToUser){
lazyLoadData();
}else{
stopLoadData();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mIsViewCreated = true;
lazyLoadData();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mIsViewCreated = false;
}
private void lazyLoadData() {
if(mIsVisibleToUser && mIsViewCreated && !mHasLoadData){
if(!mHandler.hasMessages(MSG_LOAD_DATA)){
mHandler.sendEmptyMessageDelayed(MSG_LOAD_DATA,TIME_DELAY);
}
}
}
private boolean hasLoadData(){
//增加判断是否已经加载了数据
//判断数据成员是否有值了,或者recyclerview中是否已经有子view了
return false;
}
private void stopLoadData() {
if(mHandler.hasMessages(MSG_LOAD_DATA)){
mHandler.removeMessages(MSG_LOAD_DATA);
}
}
}
网友评论