Skip to content Skip to sidebar Skip to footer

Android :save View Pager State

I am trying to save view pager state, in order to avoid creating fragments once again on orientation change. Any suggestions is highly appreciated. I tried below stuff, but not sur

Solution 1:

Example saving string in shared preferences and retrieve it again anywhere in your app.

publicclassPreferencesData {

    publicstaticvoidsaveString(Context context, String key, String value) {
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefs.edit().putString(key, value).commit();
    }

    publicstaticStringgetString(Context context, String key, String defaultValue) {
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        return sharedPrefs.getString(key, defaultValue);
    }
}

Usage:

PreferencesData.saveString(context, "mynote", "Sherlock is weird");
// retrieveStringnote= PreferencesData.getString(context, "mynote", "");

Use this to save the string on pause, and recreate it in onCreate, or where ever you need the information

The same method can easily be used for other simple types.

For your use case:

publicclassPreferencesData {

    publicstaticvoidsaveInt(Context context, String key, int value) {
        SharedPreferencessharedPrefs= PreferenceManager
                .getDefaultSharedPreferences(context);
        sharedPrefs.edit().putInt(key, value).commit();
    }

    publicstaticintgetInt(Context context, String key, int defaultValue) {
        SharedPreferencessharedPrefs= PreferenceManager
                .getDefaultSharedPreferences(context);
        return sharedPrefs.getInt(key, defaultValue);
    }
}

In your code:

    mPager = (ViewPager) findViewById(R.id.pager);
    DialerPagerAdapterviewpageradapter=newDialerPagerAdapter(fm);

    if (savedInstanceState != null) {
        if (savedInstanceState.getInt("tab") != -1) {
           // this could also be saved with PreferencesData// but if you want the app to start at the first// tab when device is restarted or recreated, this is fine.
           mPager.setCurrentItem(savedInstanceState.getInt("tab")); 
        }
    }

    // defaults to 0 if first startup after installintpagerId= PreferencesData.getInt(this, "pagerId", 0);
    mPager.setId(pagerId);

    mPager.setOnPageChangeListener(ViewPagerListener);
    mPager.setAdapter(viewpageradapter);

And in onPause()

PreferencesData.saveInt(this, "pagerId", mPager.getId());

Solution 2:

Do it this way

<activityandroid:name="yourActivityeThatContainsViewPager"android:configChanges="keyboardHidden|orientation|screenSize"
/>

Post a Comment for "Android :save View Pager State"