终于想出了解决这个问题的办法。事实证明这不是错误,而是 Android 开发人员文档中的问题/疏忽。
你看,我正在关注 PreferenceFragment 教程here。那篇文章告诉您执行以下操作以在 Activity 中实例化您的 PreferenceFragment:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
这样做的问题是,当您更改屏幕方向(或任何其他破坏并重新创建 Activity 的操作)时,您的 PreferenceFragment 将被创建两次,这就是导致它失去它的状态。
第一次创建将通过 Activity 对 super.onCreate() 的调用(如上所示)进行,它将为您的 PreferenceFragment () 调用 onActivityCreated() 方法,并为每个 Preference 调用 onRestoreInstanceState() 方法它包含了。这些将成功恢复一切的状态。
但是一旦对super.onCreate() 的调用返回,您可以看到onCreate() 方法将继续创建PreferenceFragment 秒时间。因为它被毫无意义地再次创建(这一次,没有状态信息!),所有刚刚成功恢复的状态都将被完全丢弃/丢失。这解释了为什么在 Activity 被销毁时可能显示的 DialogPreference 在 Activity 重新创建后将不再可见。
那么解决方法是什么?好吧,只需添加一个小检查以确定 PreferenceFragment 是否已创建,如下所示:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment existingFragment = getFragmentManager().findFragmentById(android.R.id.content);
if (existingFragment == null || !existingFragment.getClass().equals(SettingsFragment.class))
{
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
}
或者另一种方法是简单地检查 onCreate() 是否意味着恢复状态,如下所示:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
{
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
}
所以我想这里学到的教训是onCreate() 具有双重作用——它可以第一次设置一个 Activity,或者它可以从更早的状态恢复。
here 的回答让我意识到了这个解决方案。