簡體   English   中英

如何在TextView中顯示SharedPreferences字符串?

[英]How to display in TextView a SharedPreferences string?

我有一個問題,我已經借助EditText和Button完成了在SharedPreferences中保存字符串所需的所有代碼,但是我不知道如何永久地在TextView中檢索和顯示它,下面我都有代碼xml和java。

<EditText
    android:id="@+id/edit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/hint"
    android:layout_gravity="center"/>

<Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button"
    android:layout_gravity="center"/>

<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty"
    android:layout_gravity="center" />


public class MainActivity extends AppCompatActivity {

EditText editt;
Button btn;
SharedPreferences sharedpref;
TextView textv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editt = (EditText) findViewById(R.id.edit);
    btn = (Button) findViewById(R.id.btn);
    sharedpref = getSharedPreferences("name1",MODE_PRIVATE);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String str = editt.getText().toString();
            SharedPreferences.Editor editor = sharedpref.edit();
            editor.putString("name1",str);
            editor.apply();
        }
    });
    textv = (TextView) findViewById(R.id.text1);
}

它很簡單:

// get the saved string from shared preferences
String name1 = sharedpref.getString("name1", "default value");
// set reference to the text view
textv = (TextView) findViewById(R.id.text1);
// set the string from sp as text of the textview
textv.setText(name1);

將這些行放入新方法中,例如updateNameTextView() ,然后在onCreate和單擊偵聽器中對其進行調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM