动态添加选项到列表首选项

Dynamically adding options to a listpreference

我正在编写一个包含 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 地址,然后将其作为额外选项添加到下拉列表中。

我有一个可行的解决方案,涉及加载外部文件、清除条目并从文件中添加条目。这是 'ok' 但我想使用 sharedpreferences 来保存这些额外的值。我的问题是,如何使用编辑器编写每次启动应用程序时都会保存的额外选项?

我查看过使用 EditorputStringSetcommit,但添加的选项没有出现在下拉列表中。有相关帖子似乎处理 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;
            }
        });

写入共享首选项

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("highscore", 5);
editor.commit();

阅读自:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = 0;
long highScore = sharedPref.getInt("highscore"), defaultValue);

这是你要问的吗?

编辑:

查看您的代码,您似乎缺少实际的保存。

查看 Gregor 的回答: How to add new value to listpreference and save it?

他基本上是说,每次您打开对话框时,都会加载 xml 中的列表。您需要更改行为以包含来自 SharedPreferences 的首选项。

You can change this behavior using the setEntries() and setEntryVaues() methods of ListPreference