Android ViewPager + fragment 实现懒加载及原理解析
1 代码实现
fragment 实现
public abstract class LazyFragment extends LogFragment {
private View viewRoot;
private boolean isShow;
private boolean isLoaded;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
viewRoot = inflater.inflate(getLayoutId(), container, false);
initView(viewRoot);
if (!isShow && getUserVisibleHint()) {
dispatchVisibleHint(true);
}
return viewRoot;
}
protected abstract int getLayoutId();
protected abstract void initView(View viewRoot);
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (viewRoot != null) {
if (!isShow && isVisibleToUser) {
dispatchVisibleHint(true);
} else if (isShow && !isVisibleToUser) {
dispatchVisibleHint(false);
}
}
}
private void dispatchVisibleHint(boolean isVisible) {
isShow = isVisible;
if (isVisible) {
if (!isLoaded) {
Log.e(TAG, "开始加载" + getClass().getName());
isLoaded = true;
loadData();
}
} else {
Log.e(TAG, "停止加载" + getClass().getName());
stopLoadData();
}
}
protected void stopLoadData() {
}
protected void loadData() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
viewRoot = null;
isShow = false;
isLoaded = false;
}
}
使用
public class SecondActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
private ArrayList<LazyFragment> fragments;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initView();
}
private void initView() {
fragments = new ArrayList<>();
viewPager = findViewById(R.id.activity_second_viewPager);
tabLayout = findViewById(R.id.activity_tabLayout);
fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3());
fragments.add(new Fragment4());
fragments.add(new Fragment6());
FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager