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

问题描述 投票:1回答:1

我是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());
                                }

但是点击按钮它也会重新加载活动,以便不保存新值,如何保存更改后的值?

android textview
1个回答
0
投票

一种选择是使用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);
© www.soinside.com 2019 - 2024. All rights reserved.