我正在編寫一個程序,它具有PreferenceActivity
和多個PreferenceFragment
。用戶選擇的一個選項是要連接的服務器,這是從XML填充的。動態地將選項添加到列表首選項
<string-array name="server_names">
<item>test</item>
<item>item1</item>
<item>item2</item>
</string-array>
<string-array name="server_addresses">
<item>10.10.10.1</item>
<item>10.10.10.2</item>
<item>10.10.10.3</item>
</string-array>
這顯然工作正常,你會得到列表中的三個名字。然而,有一個單獨的片段允許用戶輸入名稱和IP地址,然後將其添加到下拉列表中作爲額外選項。
我有一個工作解決方案,涉及加載外部文件,清除條目並添加文件中的條目。這是'好',但我想用sharedpreferences
來保存這些額外的值。我的問題是,如何使用編輯器編寫額外的選項,每次啓動應用程序時都會保存這些選項?
我已經看過使用Editor
,putStringSet
和commit
但添加的選項不會出現在下拉列表中。有相關的帖子似乎與TextPreference
有關,但這些解決方案尚未解決我的問題。
編輯,這是我如何創建我的ListPreference:
<ListPreference
android:entries="@array/server_names"
android:entryValues="@array/server_addresses"
android:key="@string/countryListId"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_select_com_target"
android:enabled="true"
android:shouldDisableView="false" />
我有一個標籤上單擊處理程序添加到ListPreference:
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(getActivity())
.setTitle("Add new server")
.setMessage("Confirm you wish to add the server?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
/* command in here to edit the server_names and server_addresses */
}})
.setNegativeButton(android.R.string.no, null).show();
return true;
}
});
你設法解決它ListPreference的方法,這種行爲? – CantThinkOfAnything
我認爲你給了我一個很好的領導,我現在正在嘗試一些東西。我相信我誤解了SharedPreferences與DefaultSharedPreferences。我正在調查使用setEntries,並會接受答案,如果這樣的作品..感謝您的幫助! – Dustybin80
你成功了嗎? :D – CantThinkOfAnything