gpt4 book ai didi

Android setResult 不匹配 onActivityResult

转载 作者:行者123 更新时间:2023-11-29 17:04:54 31 4
gpt4 key购买 nike

我正在开发一个涉及两个 Activity 的测验应用程序:一个显示 Question 列表的 QuizActivity 和一个 QuestionActivity显示问题的详细信息(提示、选项等)。在 QuizActivity 中,我使用了 startActivityForResult(Intent, int) 方法来打开 QuestionActivity,如下所示:

Intent questionIntent = new Intent(QuizActivity.this, QuestionActivity.class);
questionIntent.putExtra("currentQuestion", currentQuestion);
startActivityForResult(questionIntent, REQUEST_CODE_SELECTED_OPTION);

其中 REQUEST_CODE_SELECTED_OPTION 是设置为 1 的常量。

QuestionActivity 完成后,它应该返回所选选项的索引(假设它是一个多项选择题)所以我覆盖了 onPause() 回调:

@Override
public void onPause() {
super.onPause();
Intent returnIntent = new Intent(QuestionActivity.this, QuizActivity.class);
if (curQuestion.selected()) {
returnIntent.putExtra("Result Code", RESULT_OK);
setResult(Activity.RESULT_OK, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_OK);
} else {
returnIntent.putExtra("Result Code", RESULT_CANCELED);
setResult(Activity.RESULT_CANCELED, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_CANCELED);
}
}

我还在我的 QuizActivity 中实现了 onActivityResult(int, int, Intent) 回调:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("QuizActivity", "Received result code: " + resultCode);
Log.d("QuizActivity", "Result code from intent: " + data.getIntExtra("Result Code", 100));
if (requestCode == REQUEST_CODE_SELECTED_OPTION) {
if(resultCode == Activity.RESULT_OK){
Log.d("QuizActivity", "Got RESULT_OK");
}
if (resultCode == Activity.RESULT_CANCELED) {
// do nothing
}
}
}

但是,当我运行该应用程序时,输入 QuestionActivity,选择一个选项,点击返回,从日志中我看到在 QuestionActivity 中结果代码被正确设置为-1:

D/QuestionActivity: Returned with -1
D/QuizActivity: Received result code: 0

但在 onActivityResult(int, int, Intent) 方法中,结果代码为 0。此外,我还尝试在传回的 Intent 中放入一个 int ,但在 QuizActivity 中,接收到的 Intent 是 null。我真的很困惑。我是不是用错了方法?

最佳答案

我想通了。根据这个post和 Android 文档,必须在 Activity 完成之前调用 setResult(int, Intent) 方法(即在调用 onPause()onStop()onDestroy。我尝试将它放在 onBackPressed() 中,但最初没有工作,因为我调用了 super.onBackPressed() 在第一行。最后,这成功了:

@Override
public void onBackPressed() {
Intent returnIntent = new Intent(QuestionActivity.this, QuizActivity.class);
if (curQuestion.selected()) {
returnIntent.putExtra("Result Code", RESULT_OK);
setResult(Activity.RESULT_OK, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_OK);
} else {
returnIntent.putExtra("Result Code", RESULT_CANCELED);
setResult(Activity.RESULT_CANCELED, returnIntent);
Log.d("QuestionActivity", "Returned with " + Activity.RESULT_CANCELED);
}
super.onBackPressed();
}

关于Android setResult 不匹配 onActivityResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050067/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com