简体   繁体   中英

Android - How to prevent ViewPager's Loader restarting on configuration change?

I have followed these steps to create a ViewPager , but I have the problem that the loader is restarted when the device configuration changes (eg, device rotation).

Not only does this result in an unnecessary query, but it also results in a resetting the UI by taking the user back to the first item (ie, away from the item they were viewing before they rotated their device).

I've tried calling setRetainInstance(true) on the fragment that is returned by the getItem() method of my ScreenSlidePagerAdapter class, but it hasn't helped.

There is a similar question here but am expecting / hoping there is a better solution??

With the help of this article (in particular, this part ), I have found the solution.

Firstly, I had not called...

getLoaderManager().initLoader(MY_LOADER_ID, null, this);

...in my activity's onCreate method. But I only achieved the correct behaviour if I called...

getLoaderManager().restartLoader(MY_LOADER_ID, args, this);

...on only the first time the activity is run. This was the only way to stop a new query from being performed.

So, here is the snippet from my activity's onCreate method (which I placed right after creating my ViewPager and ScreenSlidePagerAdapter )...

getLoaderManager().initLoader(LOADER_ID_NORMAL, null, this);

boolean isFirstCreate = (savedInstanceState == null);
if (isFirstCreate) {

    /*
     * If this Activity was launched with a search intent, then perform the search
     */
    parseIntent(getIntent()); //calls getLoaderManager().restartLoader()
}
else {

    /*
     * Hide the progress view
     */
    searchProgressBar.setVisibility(View.INVISIBLE);
}

Works properly for me, and seems like a fairly clean solution - but any other suggestions appreciated.

Update: 02 August 2015

Based on my comment, I think this is the right way of doing it:

if (getLoaderManager().getLoader(LOADER_ID_NORMAL) == null) {

    /*
     * Loader doesn't exist, so create and start it
     */ 
    Bundle args = ...;
    getLoaderManager().restartLoader(LOADER_ID_NORMAL, args, this); //calls onCreateLoader()
}
else {

    /*
     * Loader already exists so all we need to do is initialise it
     */
    getLoaderManager().initLoader(LOADER_ID_NORMAL, null, this); //calls onCreateLoader()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM