How To Load Fragment Data Only When Its Tab Selected

Please follow and like us:

How To Load Fragment Data Only When Its Tab Selected

All Android developers have faced automatically load previous/next tab’s data automatically issue during implementing tabs in their android applications. But we can stop this for Material Tabs or PageSlidingTabStrip Tabs by adding “setUserVisibleHint” method. Add This method to all your tab;s fragment and load all operation using this method. this method load fragment data only when its tab selected so it load one tab at each time.

// initialize boolean to know tab is already loaded or load first time

private boolean isFragmentLoaded=false;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && !isFragmentLoaded ) {
        // Load your data here or do network operations here
        isFragmentLoaded = true;
    }
}

Here we used “isFragmentLoaded” boolean to know tab is already loaded or first time. so we can stop to load fragment’s data every time.

 

That’s it : )
Hope you like our simple Android Tutorial about “Load Fragment Data Only When its Tab selected”. Stay connected for latest Android related tutorials.

nirav kalola