说到ViewPager, 有2个问题1、ViewPager默认会初始化几个fragment? 2、FragmentPagerAdapter和FragmentStatePagerAdapter的区别?
本文所说的类都是v4包下的, 如android.support.v4.view.ViewPager。 我们看google对ViewPager类的注释, 这里要更正一下, 要使用v4包下的android.support.v4.app.Fragment。 而FragmentPagerAdapter和FragmentStatePagerAdapter的基类都是PagerAdapter, google官方注释了FragmentPagerAdapter适用于3~4个fragment,FragmentStatePagerAdapter适用于有很多的fragment(类似于listview似的释放内存)。
ViewPager类默认只缓存前一个和后一个fragment(private static final int DEFAULT_OFFSCREEN_PAGES = 1;), 例如有3个tab页, 当调用ViewPager的setAdapter方法(FragmentPagerAdapter对象), 默认会初始化第一、第二页fragment, 当滑动到第二页时会实例化第三页, 当切换到第三页时会释放第一页。
注意:ViewPager左右滑动时, 划到当前fragment时不会执行当前fragment某个函数, 如果想做什么操作, 需要在ViewPager的onPageSelected函数里调用fragment的方法更新状态。
如果不想释放fragment, 就可以调用ViewPager的setOffscreenPageLimit方法设置缓存数量, 从函数注释可以看出它的作用是设置前后各缓存几个fragment。 优点是加载快, 缺点是占内存, google推荐viewpager有3或4个fragment时可以使用缓存。
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.
You should keep this limit low, especially if your pages have complex layouts. This setting defaults to 1.
-
Parameters:
-
limit
How many pages will be kept offscreen in an idle state.
public void setOffscreenPageLimit(int limit)
摘自:http://www.grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/support/v4/view/ViewPager.java#ViewPager.0mOffscreenPageLimit
ViewPager is most often used in conjunction with
, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These areandroid.app.Fragment
and android.support.v4.app.FragmentPagerAdapter
; each of these classes have simple code showing how to build a full user interface with them.android.support.v4.app.FragmentStatePagerAdapter
测试代码:
public class MainActivity extends AppComp