首页 > 解决方案 > 如何使用 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);
   }
}

标签: javaandroid

解决方案


首先你将你的名字存储在命名 函数中

  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", "");

推荐阅读