java - 如何使用 EditText 设置的 SharedPreferences 保存按钮文本
问题描述
我通过 editText 和长按钮单击设置了按钮文本。之后 editText 再次设置为空字符串。如何在 SharedPreferences 中保存按钮名称(我猜是字符串)并在重新启动应用程序时读取它?
package com.example.myapplication;
import ...
public class MainActivity<button1> extends AppCompatActivity {
Button button
EditText editText1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button3);
button.setOnClickListener(v -> opensecondone());
button.setOnLongClickListener(v -> naming());
editText1 = (EditText) findViewById(R.id.tv_textView);
}
public boolean naming() {
button = this.findViewById(R.id.button3);
button.setText(editText1.getText().toString());
editText1.setText(" ");
return true;
}
public void opensecondone() {
Intent intent = new Intent(this, firmaeins.class);
startActivity(intent);
}
}
解决方案
首先你将你的名字存储在命名 函数中
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourMessageKey", message);
editor.commit();
然后你在你的 oncreate 活动中得到值:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString("yourMessageKey", "");
推荐阅读
- javascript - 我正在尝试将提供不和谐机器人的反应转换为在使用特定反应时发送消息的机器人。我无法让它回应
- google-chrome - 字体在 Firefox 中看起来更大
- google-apps-script - 通过 Google Apps 脚本安全地调用 Google Cloud 函数
- angular - 如何在 WebStorm / PhpStorm 中启用自定义 Angular 库的自动导入?
- c# - 将 2 个不同 texbox 中的 2 个 txt 文件从小写转换为大写
- java - 从java应用程序(mysql,javafx)插入时出现阿拉伯语数据问题
- batch-file - 将带空格的文件名批量输出到不带引号的文件
- node.js - “字符串”类型的表达式不能用于索引类型“请求”
' - spotfire - 如果行中存在特定字符串 + 值,则使用 Case 语句输出值
- android - Android Kotlin 返回 setOnQueryTextListener