重新加载上次使用应用程序时的分数

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

我正在制作一个赚钱应用程序。

当用户单击“getcoins”按钮时,在

int amount = 0
amount = amount +500
textview.setText(String.valueof(amount));
的帮助下,将在文本视图中添加 500 个硬币。

问题: 当我重新启动应用程序时,计数从零开始,而不是从用户获得旧分数的位置开始。

我将文本视图存储在共享偏好中。

java android increment
1个回答
0
投票

您必须始终将新值保存在 SharedPreferences 中。 下面的代码会对您有所帮助。当您重新启动应用程序时,它将在 TextView 中显示新值。

SharedPreferences prefs = getSharedPreferences("SavedValue", MODE_PRIVATE);
int amount = prefs.getInt("totalCoins", 0);

textView.setText(String.valueOf(amount));

getcoinsButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        amount += 500;

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("totalCoins", amount);
        editor.apply();

        textView.setText(String.valueOf(amount));
    }
});

修改答案

public class MainActivity extends AppCompatActivity {

    private static final String PREFS_NAME = "SavedValue";
    private static final String COIN_COUNT_KEY = "coinCount";

    private TextView coinTextView;
    private int coinCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        coinTextView = findViewById(R.id.coinTextView);
        Button getCoinsButton = findViewById(R.id.getCoinsButton);

        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        coinCount = prefs.getInt(COIN_COUNT_KEY, 0);

        coinTextView.setText(String.valueOf(coinCount));

        getCoinsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                coinCount += 500;

                coinTextView.setText(String.valueOf(coinCount));

                SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
                editor.putInt(COIN_COUNT_KEY, coinCount);
                editor.apply();
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.