我是一个在Android Studio中进行测验的noobie,我正在尝试在活动之间传递一个整数,以增加最后他们正确的问题数量,但是在第二个活动中,当我回答第一个活动时,它并没有改变问题正确。
Question1 activity:
public class Question1 extends AppCompatActivity {
public int correctAnswers = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
Intent intent = new Intent(Question1.this, Question2.class);
Intent i = getIntent();
Intent answersCorrect = new Intent(Question1.this, Question2.class);
answersCorrect.putExtra("correctAnswers", correctAnswers);
}
public void submitQuestion1(View view) {
EditText question1TextInput = (EditText) findViewById(R.id.question1TextInput);
if (question1TextInput.getText().toString().length() >= 1) {
startActivity(new Intent(Question1.this, Question2.class));
if (question1TextInput.getText().toString().toUpperCase().contentEquals("FATHER")) {
correctAnswers += 1;
Intent answersCorrect = new Intent(Question1.this, Question2.class);
answersCorrect.putExtra("correctAnswers", correctAnswers);
}
}
}
}
Question2活动:
public class Question2 extends AppCompatActivity {
public int correctAnswers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
Intent intent = getIntent();
int number = intent.getIntExtra("correctAnswers", 0);
TextView myAwesomeTextView = (TextView)findViewById(R.id.text);
myAwesomeTextView.setText(String.valueOf(number));
}
}
最佳答案
您在这里复制您的意图:
Intent intent = new Intent(Question1.this, Question2.class);
Intent i = getIntent();
Intent answersCorrect = new Intent(Question1.this, Question2.class);
answersCorrect.putExtra("correctAnswers", correctAnswers);
替换为:
Intent intent = new Intent(Question1.this, Question2.class);
intent.putExtra("correctAnswers", correctAnswers);
startActivity(intent);
在您的第二个活动中:
int correctAnswers;
correctAnswers = (int) getIntent().getIntExtra("correctAnswers", 0);