如何在Android上将我的分数从一个活动转移到另一个活动?

时间:2011-08-05 10:32:47

标签: android android-activity

这是我使用一个活动中的整数的方式。这是一个匹配类型的问题,相应的单选按钮是答案之一。正确的单选按钮会得分为1。

Integer score1;
public void onCheckedChanged(RadioGroup group, int rb1) {
  switch(rb1){
  case R.id.radioButton1:
     score1=0;
     break;
  case R.id.radioButton2:
     score1=0;
     break;
  case R.id.radioButton3:
     score1=0;
     break;  
  case R.id.radioButton4:
     score1= 1;
     break;  
}

在结果屏幕上,我将使用这样的整数:

totalscore = score1 +score2 .....

如何将score1从带有单选按钮的活动转移到结果屏幕的活动?

2 个答案:

答案 0 :(得分:1)

尝试

Integer score1, totalscore;

public void onCheckedChange(RadioGroup group, int rb1) {
    switch (rb1) {
        case R.id.radioButton1:
            score1=0;
            break;
        case R.id.radioButton2:
            score1=0;
            break;
        case R.id.radioButton3:
            score1=0;
            break;  
        case R.id.radioButton4:
            score1= 1;
            totalscore += 1;
            break;  
     }
}

答案 1 :(得分:0)

首先,您可以大大简化switch逻辑:

Integer score1;
public void onCheckedChanged(RadioGroup group, int rb1) {
    score1 = (rb1 == R.id.radioButton4) ? 1 : 0;
}

其次,有几种不同的方法可以将score1从一个Activity传递到另一个Activity。例如,当您为第二个活动创建Intent时,您可以使用putExtra()来存储您的得分值,然后第二个活动可以使用getExtra()在启动时读取该值。

或者你可以使用任何一些快速但有问题的黑客攻击,例如使score1成为public static字段,或者通过系统属性传递它,或者将它写出来达成一致意见文件位置,或将其存储到数据库中约定的字段(这些黑客仅在每个设备只有一个活动实例时才有效,并且根本不建议这样做。)

真的,你应该坚持使用getExtra()putExtra()。沿着:

//in QuestionActivity
private Integer score1;

//...

public void onCheckedChanged(RadioGroup group, int rb1) {
    score1 = (rb1 == R.id.radioButton4) ? 1 : 0;
    Intent resultIntent = new Intent(this, ResultActivity.class);
    resultIntent.putExtra("score1", score1);
    startActivity(resultIntent);
}


//in ResultActivity
private Integer score1;

//...

@Override
protected void onStart() {
    score1 = this.getIntent().getExtras().getInt("score1");
    super.onStart();
}