我创造了一个迷你游戏。用户需要在2秒内回答我的问题,如果用户回答为真,则分数将增加1,如果用户回答错误 - 游戏结束且分数变为0。
我想使用SharedRefences,这样我可以在用户再次播放时保存分数。但它没有用。
我的CountDownTimer:
public void start_game() {
flag = false;
btnTrue.setClickable(true);
btnWrong.setClickable(true);
a = (int) (Math.random() * 6);
b = (int) (Math.random() * 6);
sum = (int) (Math.random() * 11);
tvDetails.setText(a + " + " + b + " = " + sum);
proTime.setSecondaryProgress(0);
timer = new CountDownTimer(3000, 10) {
@Override
public void onFinish() {
// TODO Auto-generated method stub
btnTrue.setClickable(false);
btnWrong.setClickable(false);
if (flag) {
tmp++;
tvScore.setText("" + tmp);
start_game();
} else {
ShowDialogs();
tmp = 0;
tvScore.setText("" + tmp);
}
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
proTime.setSecondaryProgress(proTime.getSecondaryProgress() + 10);
}
};
timer.start();
}
public void ShowDialogs() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
tvNowScore = (TextView) dialog.findViewById(R.id.NowScore);
tvHighScore = (TextView) dialog.findViewById(R.id.HighScore);
ImageView btnRep = (ImageView) dialog.findViewById(R.id.Rep);
ImageView btnExit = (ImageView) dialog.findViewById(R.id.Exit);
ResPreferences();
int HighScore = Integer.parseInt(tvHighScore.getText().toString());
int Score = Integer.parseInt(tvScore.getText().toString());
if (Score > HighScore) {
HighScore = Score;
SavingPreferences();
}
tvNowScore.setText("" + Score);
tvHighScore.setText("" + HighScore);
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
System.exit(0);
}
});
btnRep.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
dialog.cancel();
if (timer != null) {
timer.cancel();
timer = null;
}
start_game();
}
});
dialog.show();
}
比赛结束后,我无法保存比分。
这是我保存的偏好设置
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
editor.putString("HighScore", HighScore);
editor.commit();
}
这是Restrore Pre:
public void ResPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = pre.getString("HighScore", "0");
tvHighScore.setText(score);
}
答案 0 :(得分:0)
试试这个:
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = null;
if(pre.contains("HighScore")){
score = pre.getString("HighScore", "0");
}
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
if(score != null && Integer.parseInt(score) > Integer.parseInt(HighScore )){
editor.putString("HighScore", score);
} else {
editor.putString("HighScore", HighScore);
}
editor.commit();
}