我对以下代码中发生的事情感到困惑。它实际上是在做我想做的事,但我认为我必须做更多的工作。在 onCreate 方法中,即使在我强制退出应用程序之后,复选框仍会保留其上次运行的选中或未选中状态。即使从未打印日志消息“onCreate found”并且打印了“添加帐户”消息并且 cbp2.setChecked(false) 似乎被忽略,它也会保存它们的状态。
这是怎么回事?
public class SettingsActivity extends PreferenceActivity {
private final static String LOGTAG = "SettingsActivity";
@Override
@SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load preference data from XML
this.addPreferencesFromResource(R.xml.preferences_settings);
Set<String> accounts = new HashSet<String>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
accounts = Accounts.getAccounts(this);
}
final PreferenceCategory cat = (PreferenceCategory) this
.findPreference("key_accounts");
for (String account : accounts) {
final CheckBoxPreference cbp = (CheckBoxPreference) this
.findPreference("key_" + account);
if (cbp != null) {
Log.d(SettingsActivity.LOGTAG, "onCreate found: " + account
+ (cbp.isChecked() ? ", checked" : ""));
continue;
}
Log.d(SettingsActivity.LOGTAG, "adding account " + account);
final CheckBoxPreference cbp2 = new CheckBoxPreference(this);
// make sure each key is unique
cbp2.setKey("key_" + account);
cbp2.setTitle(account);
cbp2.setChecked(false);
cat.addPreference(cbp2);
}
}
}
这是我的首选项 xml 的顶部:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key = "key_accounts"
android:title = "@string/title_accounts">
</PreferenceCategory>