[英]How to display in TextView a SharedPreferences string?
I have a problem, I have completed all the code needed for saving a string in SharedPreferences with the help of an EditText and a Button but I have no idea how to retrieve and display it in a TextView permanently, below I have the code both for xml and java. 我有一个问题,我已经借助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);
}
It is simple as: 它很简单:
// 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);
Put these lines into a new method, for instance updateNameTextView()
, and call it in onCreate
and in your click listener. 将这些行放入新方法中,例如
updateNameTextView()
,然后在onCreate
和单击侦听器中对其进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.