我不知道你怎么能不理解这么简单的任务,而是为了避免一切:
我的主要观点是每次点击按钮时将得分增加1(已完成)。 我想改变增量,而是将分数增加1, 我想在点击升级按钮后将得分增加2。
目标: {MainActivity:你点击一个按钮,得分增加1. UpgradeActivity:你点击一个按钮,增量会改变,分数会立即增加2.我不能让它增加2,而不是之一。}
在app评分中,我使用SharedPreference
,MainActivity.java保存:
public void button(View view) {
mScore++;
SharedPreferences myScore = getSharedPreferences("Symbols", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myScore.edit();
editor.putInt("mScore", mScore);
editor.commit();
score.setText("Symbols: " + mScore);
}
UpgradeActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrade);
score = findViewById(R.id.score);
SharedPreferences myScore = this.getSharedPreferences("Symbols", Context.MODE_PRIVATE);
mScore = myScore.getInt("mScore", 0);
score.setText("Symbols: " + mScore);
}
public void upgrade(View view) {
if(mScore>=200){
SharedPreferences myScore = this.getSharedPreferences("Symbols", Context.MODE_PRIVATE);
mScore = myScore.getInt("mScore", 0);
mScore += 2;
score.setText("Symbols: " + mScore);
onResume();
Intent intent = new Intent(this, PlayActivity.class);
startActivity(intent);
}else{
Intent intent1 = new Intent(this, MainActivity.class);
startActivity(intent1);
}
}
}
我的观点并不奏效。它仍然会增加+1,因此我的UpgradeActivity或升级按钮可能有问题。
有什么建议吗?
答案 0 :(得分:0)
从代码中可以看出,由于mScore++
可能会将其更改为
int increment = 1;
public void button(View view) {
mScore = mScore + increment;
SharedPreferences myScore = getSharedPreferences("Symbols", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myScore.edit();
editor.putInt("mScore", mScore);
editor.commit();
score.setText("Symbols: " + mScore);
}
然后
startActivityForResult(new Intent(this, UpgradeActivity.class), 1)
在UpgradeActivity.class中
public void upgrade(View view) {
if(mScore>=200){
setResult(RESULT_OK);
}
onBackPressed();
}
然后在MainActivity.class
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
increment = 2;
}
}
}
希望这个回答你的问题/或者会给你一些想法......