2016-11-08 105 views
0

我正在編寫一個程序,它具有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,putStringSetcommit但添加的選項不會出現在下拉列表中。有相關的帖子似乎與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; 
      } 
     }); 
+0

你設法解決它ListPreference的方法,這種行爲? – CantThinkOfAnything

+0

我認爲你給了我一個很好的領導,我現在正在嘗試一些東西。我相信我誤解了SharedPreferences與DefaultSharedPreferences。我正在調查使用setEntries,並會接受答案,如果這樣的作品..感謝您的幫助! – Dustybin80

+0

你成功了嗎? :D – CantThinkOfAnything

回答

1

寫入共享PREF

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); 

這是你在問什麼?

編輯:

看你的代碼,你似乎缺少實際節電。

檢查從格雷戈爾答案: How to add new value to listpreference and save it?

他基本上說,每次你打開你的對話框中,從XML列表加載。您需要更改行爲以包含SharedPreferences中的首選項。

您可以更改使用setEntries()和 setEntryVaues()

+0

我正在從文檔看,我只是無法讓它適應ListPreference。我已經使用putStringSet,但更改不會反映在下拉列表中。 – Dustybin80

+0

當您從共享首選項讀取時,您必須將其自動添加到下拉菜單的適配器中。 – CantThinkOfAnything

+0

添加之後,您可能還需要調用notifyDatasetChanged()?不知道你的下拉列表使用了什麼樣的實現。 – CantThinkOfAnything