Android之取消ViewPage+Fragment的预加载

Android之取消ViewPage+Fragment的预加载

用过ViewPage+Fragment组合的童鞋自然知道这个问题,没有遇到的同学祝愿你们永远不会遇到,呵呵。直接上关键代码

注释:setUserVisibleHint每次fragment显示与隐藏都会调用,他的调用顺序由于onCreate,所以需要一些常量进行判断

1
2
3
4
5
6
7
8
9
10
11
12
13
private boolean mHasLoadedOnce = false;
@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (this.isVisible()) {
            // we check that the fragment is becoming visible
            if (isVisibleToUser && !mHasLoadedOnce && mArrayList==null) {
                 
                                // async http request here
                mHasLoadedOnce = true;
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }


由于setUserVisibleHint优于onCreate调用,所以当onCreate调用完毕setUserVisibleHint就不会触发,这时需要在首个显示的fragment调用setUserVisibleHint方法

1
2
3
4
5
6
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setUserVisibleHint(true);
        super.onActivityCreated(savedInstanceState);
    }

这个是设置viewpager保留多少个显示界面

1
pager.setOffscreenPageLimit(3);

posted on 2016-03-03 10:42  梦若在心就在  阅读(436)  评论(0编辑  收藏  举报

导航