【问题标题】:How to display in TextView a SharedPreferences string?如何在 TextView 中显示 SharedPreferences 字符串?
【发布时间】:2017-08-13 15:55:48
【问题描述】:

我有一个问题,我已经在 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);
}

【问题讨论】:

    标签: java android textview sharedpreferences


    【解决方案1】:

    很简单:

    // 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 和您的点击监听器中调用它。

    【讨论】:

    • 完美!谢谢,它工作正常!但是为什么不直接保留它而不创建方法和东西呢?
    • 只是因为 a) 当你启动你的应用程序时,它应该显示来自 sharedpreferences 的值,b) 当你保存一个新值时,它还应该更新 textview 中的字符串 :) 所以你有两个地方和为了避免代码重复,你把它放在一个地方(方法)并从两个地方调用这个方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2016-04-06
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多