使用過ViewPager的應該都知道,ViewPager的setoffscreenpagelimit()
方法,使用該方法能夠設置在ViewPager滑動時,左右兩側各保存多少個頁面,那咱們直接設置setoffscreenpagelimit(0)
,不就行了嗎。固然不是這樣子的,當咱們setoffscreenpagelimit(0)
時,若是細心的話,就會發現,並非只保存當前頁面,而是兩邊的頁面同時也有保存。這時候,咱們懷着疑問去閱讀源碼,纔會發現,這個方法居然是這樣寫的:java
/** * 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. * * <p>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.</p> * * <p>You should keep this limit low, especially if your pages have complex layouts. * This setting defaults to 1.</p> * * @param limit How many pages will be kept offscreen in an idle state. */ public void setOffscreenPageLimit(int limit) { if (limit < DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES); limit = DEFAULT_OFFSCREEN_PAGES; } if (limit != mOffscreenPageLimit) { mOffscreenPageLimit = limit; populate(); } }
這個方法的默認值居然是1。
這樣子,當咱們只想初始化一個頁面的時候,就要注意了。這個時候,我採用的是懶加載的方式,由於在頁面進入前臺的時候,是會調用setUserVisibleHint()
這個方法的,經過這個方法咱們能夠得到當前當前頁面是否對用戶可見,並在對用戶可見的時候進行初始化,這時還要注意一點,那就是setUserVisibleHint()
這個方法的調用並不保證View等須要的東西是否已經初始化成功,因此咱們仍是要判斷一下的。less