Android download fragment content only when visible

I have one activity that has a tabPageIndicator at the bottom of the screen. Please see screenshot... The first four icons should open up other fragments. The final icon should open an alert box with options to open other screens.

I faced two problems:

  • The ViewPager loads all 4 fragments at once, and a large amount of data is processed in the background. I would like to know if there is a way to load the content only when the fragment is visible to the user. I tried using setPageLimit but it didn't work.

  • My second problem is that I would like to ideally open the popup when the last icon is clicked, rather than opening another snippet. Is it possible?

I'm not sure if the viewPager supports snippet-free viewing.

+4


source to share


1 answer


The pager view will load snippets side by side even if you set setOffscreenPageLimit to 0. Because if the value is less than 1 they will set it to 1.

Therefore onCreate, onCreateView ... onResume of the nearest fragments will be called before it becomes visible.

So just load your data into setUserVisibleHint .

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

      

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



If you get data from arguments. We will get this data from the onCreate or onCreateView of the fragment. So the first visible chunk of setUserVisibleHint will be called with no data to load ( getView ()! = Null from 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 that will bind the data of my fragment.

Thus, for the first visible fragment, loadData will be called from onCreateView, and next to the fragment, from setUserVisibleHint.

0


source







All Articles