单击按钮后在 textview 中增加 int 并保持它抛出活动

increase int in textview after button click and keep it threw activities

我是 android 的新手,我现在被困住了。 我正在构建一个 android 应用程序。 我有一个带有 int 值的 textview

final int intbut = 40;

hp.setText(String.valueOf(intbut));

我有一个按钮,当点击它时,它会将 +1、+0 或 -1 添加到值中。

public void onClick(DialogInterface dialog, int which) {
                                    if(answer.getHp() == 1){
                                        hp.setText(String.valueOf(intbut + 1));
                                        Log.i("GameActivity", "json " + answer.getHp());
                                }

但是在点击按钮时它也会重新加载 activity 所以新值没有保存,我如何保存更改后的值?

一个选项是使用 Shared preferences 来保存所需的值并在您的应用程序的任何位置检索它。

例如,这是保存和检索整数值的创建方法:

private String PREFS_KEY = "mypreferences";

public void saveValuePref(Context context, int value) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    editor.putInt("myValue", value);
    editor.commit();
}



public int getValuePref(Context context) {
    SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    return  preferences.getInt("myValue", 0);
}

要保存值,请使用:

saveValuePref(getApplicationContext, intbut);

检索值使用:

int intbut = getValuePref(getApplicationContext);