2013-06-13 50 views
0

我希望我的應用程序在共享首選項中保存textView2。這是我保存複選框狀態的當前共享首選項代碼(選中/未選中)。如何將共享首選項中的textView保存?

private boolean getFromSP(String key){ 
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE); 
return bifrostPrefs.getBoolean(key, false); 
} 
private void saveInSp(String key,boolean value){ 
SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = bifrostPrefs.edit(); 
editor.putBoolean(key, value); 
editor.commit(); 
} 

我從來沒有真正與共享prefrences合作過,所以我真的不知道我將如何創建一個新的共享prefrence救我textview2。

+2

您無法將視圖存儲在共享首選項中。但是你可以保存字符串,所以只需要使用putString而不是putBolean,其他所有的工作都是一樣的。 –

回答

3

你不能。

的SharedPreferences類提供了一個通用框架,允許 您保存和檢索的基本數據類型 持續鍵值對。您可以使用SharedPreferences保存任何原始數據: 布爾值,浮點數,整數,長整數和字符串。

從DOC Using Shared Preferences

鋁以爲你可以存儲的TextView

//To get stored value 
    private String getString(String key){ 
     SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE); 
     return bifrostPrefs.getString(key, ""); 
    } 

的價值..

//To Save value 
    private void saveString(String key, String value){ 
     SharedPreferences bifrostPrefs = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = bifrostPrefs.edit(); 
     editor.putString(key, value); 
     editor.commit(); 
    } 

如何使用這些方法

將這個代碼,你要保存的TextView的價值

//To save value of TextView 
if (!TextUtils.isEmpty(aTextView.getText())) { 
    saveString("aTextView", aTextView.getText().toString()); 
} 

//To Read and show into TextVIew 
aTextView.setText(getString("aTextView")); 
+0

但是我會在哪裏以及如何調用這兩種方法? – Guy

+0

@ user2454356查看我的編輯 –

+0

謝謝!奇蹟般有效。我是新來的java,所以這仍然讓我困惑不已,但我希望創建越來越多的應用程序會變得更容易。 – Guy

1

您可以輕鬆將串在共享偏好:
如果您不確定如何使用共享偏好,this will be of great value to you.

至於TextViews,如何關於保存textView2.getText()
TextView.getText()顯然返回TextView顯示的文本。如果您需要其他TextView屬性,則consult this.