activity间的数据传递——使用intent extra
在QuizActivity和CheatActivity之间进行数据传递。使用以下语句的返回值通知CheatActivity当前问题的答案
mQuestionBank[mCurrentIndex].isAnswerTrue()
将该值作为extra信息,附加在传入startActivity(Intent)方法的Intent上发送出去。
1)添加extra常量
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
2)在CheatActivity中的newIntent()方法
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent intent = new Intent(packageContext, CheatActivity.class);
intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return intent;
}
3)用extra启动
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
Intent intent = CheatActivity.newIntent(QuizActivity.this, answerIsTrue);
startActivity(intent);
4)获取extra信息
private boolean mAnswerIsTrue;
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
5)提供看答案的机会
private TextView mAnswerTextView;
private Button mShowAnswerButton;
mAnswerTextView = (TextView) findViewById(R.id.answer_text_view);
mShowAnswerButton = (Button) findViewById(R.id.show_answer_button);
mShowAnswerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
6)从子activity获取返回结果
//调用startActivityForResult()方法
startActivityForResult(intent, REQUEST_CODE_CHEAT);
//设置结果值
private static final String EXTRA_ANSWER_SHOWN =
"com.bignerdranch.android.geoquiz.answer_shown";
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
//解析结果intent
public static boolean wasAnswerShown(Intent result) {
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
//onActivityResult()方法的实现
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null) {
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
//基于mIsCheater变量值改变toast消息
if (mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}