我需要一个包含多个联系方式的首选项屏幕。所以我默认有 1 个和一个按钮“添加联系人”来添加其他联系人。出于某种原因,一切都很好,但是当我再次访问设置时,新的偏好没有出现。
当我添加联系人时,所有首选项都会显示 - 并且可以输入数据。但是当我退出并重新输入首选项时,一切都消失了。只有联系人 1 显示。
public class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
public PreferenceScreen root;
@SuppressWarnings("deprecation")
public PreferenceScreen createPreferenceHierarchy() {
PreferenceCategory userDetails = new PreferenceCategory(this);
userDetails.setTitle("User Details");
userDetails.setKey("userdetails");
root.addPreference(userDetails);
EditTextPreference userName = new EditTextPreference(this);
userName.setTitle("User Name");
userName.setSummary("Please enter your full name");
userName.setDialogTitle("Please enter your name");
userName.setKey("userName");
userDetails.addPreference(userName);
EditTextPreference contactCount = new EditTextPreference(this);
contactCount.setTitle("Count");
contactCount.setEnabled(false);
contactCount.setKey("contactcount");
userDetails.addPreference(contactCount);
PreferenceCategory contact1 = new PreferenceCategory(this);
contact1.setTitle("Emergency Contact 1");
contact1.setKey("contact1");
contact1.setSummary("Add emergency contact details");
root.addPreference(contact1);
EditTextPreference contactName1 = new EditTextPreference(this);
contactName1.setTitle("Name");
contactName1.setSummary("Emergency Contact Name");
contactName1.setDialogTitle("Please enter the name");
contactName1.setKey("contactname1");
contact1.addPreference(contactName1);
ListView v = getListView();
Button button = new Button(this);
button.setText("Add Contact");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int count = Integer.parseInt(root.getPreferenceManager()
.getSharedPreferences().getString("count", "1"));
int nextCount = count + 1;
EditTextPreference contactName = new EditTextPreference(
SettingsActivity.this);
contactName.setKey("contactname" + nextCount);
contactName.setTitle("Email ID");
contactName.setSummary("Emergency Contact's Name");
PreferenceCategory preferenceCategory = new PreferenceCategory(
SettingsActivity.this);
preferenceCategory.setKey("contact" + nextCount);
preferenceCategory.setTitle("Emergency Contact" + nextCount);
preferenceCategory.setSummary("Add emergency contact details");
root.addPreference(preferenceCategory);
root.addPreference(contactName);
Editor editor = root.getPreferenceManager()
.getSharedPreferences().edit();
editor.putString("count", Integer.toString(++count));
editor.commit();
}
});
v.addFooterView(button);
return root;
}
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.root = getPreferenceManager().createPreferenceScreen(
SettingsActivity.this);
this.setPreferenceScreen(createPreferenceHierarchy());
}
}
所以基本上,通过按钮单击添加的新联系人下次不会出现。我需要把它保存在某个地方吗?我究竟做错了什么?