Stop Android TabLayout loading next page automatically

Deadly 提交于 2019-12-20 03:55:09

问题


I've realized when using a tab layout in Android it always loads the tabs touching it, i.e. the tab before and the tab after so it is loaded when you page to it.

However, I load lots of content and images from a server and this causes a lot of data and memory use and I often get OOM errors, I am displaying the images efficiently using Glide.

Basically I need to know 3 things:

  1. How can I stop the tab layout loading any pages other than the current one
  2. How to clear/recycle/delete an old tab after you get to a new page to clear up memory
  3. How to always refresh the tab when you go back to it

回答1:


By default it is viewpager.setOffscreenPageLimit(1) , meaning View pager will by default load atleast 1 on the right and one on the left tab of current tab. It is done so, mostly because there is a point when u slide viewpager, when certain area of both tabs is visible. For those smooth transitions preloading is required. You cannot set it viewpager.setOffscreenPageLimit(0). The only way out is to use this method setUserVisibleHint add this to your fragment

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

This will be called only when that particular tab is visible to user, so only then u can call all loadfing function. Hope it helps.



来源:https://stackoverflow.com/questions/36353560/stop-android-tablayout-loading-next-page-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!