startActivityForResult 的问题
我有一个活动启动另一个具有 EditText 视图的活动。当用户单击“后退”按钮时,我希望返回此编辑文本视图中的字符串,但我无法让它工作。我尝试实现一个按钮(测试目的)并运行我的代码,然后它就可以工作了。
在启动另一个活动的活动中:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE_COMMENT == requestCode) {
if (RESULT_OK == resultCode) {
Toast.makeText(this, data.getDataString(), Toast.LENGTH_LONG).show();
}
}
}
具有编辑文本视图的活动(我希望它能够工作):
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.setData(Uri.parse("hfldskajfkj" + commentEditText.getText().toString()));
setResult(RESULT_OK, intent);
}
但是当我记录它时,结果代码是 0 (RESULT_CANCELLED)。
I have one activity with that launches another activity that has a EditText-view. When the user clicks the "Back" button I want the string in this edit text view to be returned but I can't get it to work. I tried to implement a button (test purpose) and running my code and then it works.
In the activity that launches the other one:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE_COMMENT == requestCode) {
if (RESULT_OK == resultCode) {
Toast.makeText(this, data.getDataString(), Toast.LENGTH_LONG).show();
}
}
}
The activity with the edit text view (I want this to work):
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.setData(Uri.parse("hfldskajfkj" + commentEditText.getText().toString()));
setResult(RESULT_OK, intent);
}
But the resultCode is 0 (RESULT_CANCELLED) when i log it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是
onBackPressed()
的默认实现(也在 文档)。这意味着您的活动在调用其他代码之前已完成(使用默认代码RESULT_CANCELLED
)。删除super.onBackPressed()
并在底部添加finish()
应该可以解决此问题。Thats the default implementation of
onBackPressed()
(also mentioned in the documentation). This means your activity gets finished (with the default codeRESULT_CANCELLED
) before your other code gets invoked. Removingsuper.onBackPressed()
and addingfinish()
on the bottom should fix this.问题是这样的: API 说:
当您调用 super.onBackPressed() 时,对特定活动的所有引用都将被清除。因此,未添加特定数据。尝试在按钮的 OnClickListener 中插入相同的代码。那应该有效
The problem is this: The API says:
And when you call super.onBackPressed() all the references to the particular activity are cleared. Hence the particular data is not added. Try the same code inserted in OnClickListener of a button. That should work
Android UI 指南中的某个地方说你不应该有明确的“保存”按钮。在这种情况下,答案很简单:不必费心检查结果代码是否为 RESULT_OK,无论如何,始终使用 EditText 小部件的最后一个值。
Somewhere in the Android UI guidelines it says you should not have explicit “save” buttons. In this case, the answer is simple: don’t bother checking if the result code is RESULT_OK, always use the last value of the EditText widget regardless.