2013-07-24 28 views
0

我有一個EditTextPreference,我不知道該字符串何時被保存到Shared Preferences文件。什麼時候首選項保存到文件?

如果我從一個空字符串開始,並將其更改爲「Hello」,那麼此更新何時纔會保存?我需要手動保存嗎?

+2

正確的答案給喬爾而不是我,正如Geobits指出的那樣;-) – Darwind

回答

2

我有一個EditTextPreference,當它提交該字符串 到共享首選項文件

不知道

如果您查看EditTextPreference文檔,則會在調用setText(String)方法時保存文本。此方法提交將文本保存到SharedPreferences。在您調用該方法之前,首選項將永遠不會更新。例如...

EditTextPreference mPrefs = ... 

//perform any manipulations on the string, not saved until you call setText() 
String mText = "2"; 
mText += " + 2"; 
mText += " = 4"; 

// saves "2 + 2 = 4" to SharedPreferences 
mPrefs.setText(mText); 
1

當您提交時,通過調用Editor.commit()Editor.apply()

參見documentation

+2

這顯然是錯誤的。這適用於使用'SharedPreferences.Editor',但與'EditTextPreference'無關。喬爾的回答是正確的;當你調用'setText()'時,它會保存到'SharedPreferences'中。 – Geobits

+0

你是對的 - 對不起,我不知道我怎麼會錯過這個問題的部分 - 猜我有點快回答 - 給喬爾正確的答案;-)然而,「幕後」,當你調用'setText(text)'時,調用'Editor.commit()';-) – Darwind

+0

這是真的!在幕後,這些電話正在製作中。但是,這有點超出了他的問題範圍 – Joel

1

在源尋找EditTextPreference.java,字符串在setText()方法仍然存在。

因此,它將在文本更改後提交給SharedPreferences文件。

0

當u編輯prefrence你可以使用下面的代碼:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); 


Editor edit = sp.edit(); 
edit.putString("Preference_Label", variable_name); 
edit.commit(); // this commits the edit 
相關問題