[英]SharedPreferences for save the value of TextView?
我有一個帶有三個片段的ViewPager。 在第一個片段中,我有一個Button,如果按則顯示兩個TextView,它們帶有不同的文本。 如果我轉到第三個片段,然后回到第一個片段,則看不到更多的TextView。 我了解到您必須使用SharedPreferences不會丟失該值,然后我編寫了這段代碼,但是它不起作用。
TextView1=(TextView)view.findViewById(R.id.textView1);
TextView2=(TextView)view.findViewById(R.id.textView2;
Button b1 = (Button) view.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// CODE HERE
SharedPreferences prefs = this.getSharedPreferences(
"com.MyPackage.AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("TextView1",TextView1.getText().toString());
editor.putString("TextView2",TextView2.getText().toString());
editor.commit();
});
為什么不起作用? 如果我關閉應用程序時想要刪除SharedPreferences中存儲的值,該怎么辦?
要寫入SharedPref,可以使用以下代碼:
String text = "Your text here";
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
appPrefs.setSessionId(text);
要從SharedPref中讀取,可以使用以下命令:
String textViewTextHolder = appPrefs.getSessionId();
您應該考慮將靜態變量用於要執行的操作:
靜態變量示例:
public static int i = 1;
要在另一個活動中訪問它:
if(MainActivity.i == 1){
}
如果您出於任何原因要堅持使用共享首選項,則可以在應用啟動時將其清除,盡管我建議您不要對自己的工作使用共享首選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.