【发布时间】:2016-10-17 01:55:48
【问题描述】:
我不知道如何解决这个问题,请帮忙!
我正在创建一个计数器应用程序,每次用户按下按钮时都会显示数字。它从 0 开始,最大为 9999。我的问题是,在用户关闭应用程序后,它再次从 0 开始,但我想要的是在用户再次打开应用程序时显示用户按下的最后一个数字而不是 0。我尝试了许多共享偏好代码,但没有一个有效。这是我的代码:
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int x;
Context context = this;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
mp = MediaPlayer.create(context, R.raw.button_press);
number.setText(String.format("%04d", x)+"");
btn_count.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x = x +1;
number.setText(String.format("%04d", x)+"");
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x=0;
number.setText(String.format("%04d", x)+"");
}
});
}
}
【问题讨论】:
-
也添加您的共享偏好代码。
标签: java android integer sharedpreferences