# 基本使用

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

Implementation of PagerAdapter that uses a Fragment to manage each page. This class also handles saving and restoring of fragment’s state.

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

“Talk is cheap, show me the code.” 如果这样表达还是不能理解二者之间的区别的话，最好的办法就是用代码来表达。

setUserVisibleHint 和 各个生命周期函数，添加日志打印。然后新建四个子类，分别命名为 OneFragment、TwoFragment、ThreeFragment 和 FourFragment，按照基本使用方法写好代码，运行并滑动页面，查看日志打印。

# Fragment 懒加载

ViewPager 本质上是通过 Fragment 调用 setUserVisibleHint 方法实现 Fragment 页面的展示与隐藏，这一点从FragmentPagerAdapterFragmentStatePagerAdapter 的源码和上面的截图中都可以看出。那么对应的解决方案就有了，自定义一个 LazyLoadFragment 基类，利用 setUserVisibleHint 和 生命周期方法，通过对 Fragment 状态判断，进行数据加载，并将数据加载的接口提供开放出去，供子类使用。参考代码如下：