天天看點

用ViewPager布局,但是又不想預加載的問題

​問題背景:

    ViewPager是常用來做tab分頁布局的一個元件,程式員常用ViewPager+Fragment來做整體布局

問題描述:

    有時候在某個頁面顯示的時候,會去加載一些資料,但這些資料在某些情況下又是不需要加載的,如果程式員習慣将這個加載操作放在Fragment的CreateView中,因為ViewPager會預加載頁面以便滑動,則會造成這些資料在不恰當的時候過早的被加載調用,此時,即便是将ViewPager的setOffscreenPageLimit(0)設定為0也是無效的,因為ViewPager為了避免滾動時出現空頁的情況,無視了為0這種操作

解決方案:

官方對此函數的解釋:

Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.

An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.

大意:這個函數是系統決定fragment是否呈現在使用者面前的一個提示。當fragment滑動出可視範圍是,會被設定為false,反之則為true,這個函數可以用于fragment顯示給使用者看是,處理一些更新或加載的行為

繼續閱讀