我正在尝试保存查看寻呼机状态,以避免在方向更改时再次创建片段。任何建议都非常感谢。
我尝试了以下内容,但不确定它是如何工作的......
int pagerId = 0;
mPager = (ViewPager) findViewById(R.id.pager);
DialerPagerAdapter viewpageradapter = new DialerPagerAdapter(fm);
if (savedInstanceState != null) {
if (savedInstanceState.getInt("tab") != -1) {
mPager.setCurrentItem(savedInstanceState.getInt("tab"));
pagerId=savedInstanceState.getInt("pagerState");
}
}
mPager.setOnPageChangeListener(ViewPagerListener);
if (pagerId != -1 ){
mPager.setId(pagerId);
}else{
pagerId=mPager.getId();
}
mPager.setAdapter(viewpageradapter);
在saveInstanceState中的我正在做下面的事情
outState.putInt("pagerState" , mPager.getId() );
由于 Venkatraman
答案 0 :(得分:0)
这样做
<activity
android:name="yourActivityeThatContainsViewPager"
android:configChanges="keyboardHidden|orientation|screenSize"
/>
答案 1 :(得分:-1)
示例在共享偏好设置中保存字符串,然后在应用中的任意位置再次检索它。
public class PreferencesData {
public static void saveString(Context context, String key, String value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putString(key, value).commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getString(key, defaultValue);
}
}
用法:
PreferencesData.saveString(context, "mynote", "Sherlock is weird");
// retrieve
String note = PreferencesData.getString(context, "mynote", "");
使用此命令在暂停时保存字符串,并在onCreate中重新创建它,或者在需要信息的地方重新创建
同样的方法可以很容易地用于其他简单类型。
对于您的用例:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
在您的代码中:
mPager = (ViewPager) findViewById(R.id.pager);
DialerPagerAdapter viewpageradapter = new DialerPagerAdapter(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 install
int pagerId = PreferencesData.getInt(this, "pagerId", 0);
mPager.setId(pagerId);
mPager.setOnPageChangeListener(ViewPagerListener);
mPager.setAdapter(viewpageradapter);
在onPause()
PreferencesData.saveInt(this, "pagerId", mPager.getId());