How to only call onCreateView when fragment is visible?

前端 未结 3 1015
野性不改
野性不改 2020-12-22 09:55

I\'m using a ViewPager with 5 fragments and my problem is that when the first fragment is visible, it already loads the second one.

I read something

3条回答
  •  渐次进展
    2020-12-22 10:46

    View pager will load the near by fragments, even if you set setOffscreenPageLimit to 0. Since if the value is less than 1, they will set it as 1.

    So onCreate, onCreateView... onResume of the near by fragments will be called before it is visible.

    So just load your data in setUserVisibleHint.

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getView() != null && isVisibleToUser){
            loadData();
        }
    }
    

    But there exists a problem. This method(setUserVisibleHint) will be called before the onCreate of our fragment.

    If you get the data from arguments.. We will get those data from onCreate or onCreateView of fragment. So the first visible fragment's setUserVisibleHint will be called, without data to load(getView() != null from the above method). For this we can use

     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater,container,savedInstanceState);
    
        // This is because for the first fragment to loadData, since the 
        // setUserVisibleHint is called before the onCreateView of the fragment.
    
        if(getUserVisibleHint()){
            loadData();
        }
    
        return view;
    }
    

    loadData is the method which will do data binding part of my fragment.

    By doing this, For the first visible fragment loadData will be called from onCreateView and near by fragment it will be called from setUserVisibleHint.

提交回复
热议问题