将数据发送回 Android 中的 Main Activity [英] Sending data back to the Main Activity in Android
问题描述
我有两个活动:主要活动和子活动.
当我按下主活动中的按钮时,子活动就会启动.
I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.
现在我想将一些数据发送回主屏幕.我使用了 Bundle 类,但它不起作用.它会抛出一些运行时异常.
Now I want to send some data back to the main screen. I used the Bundle class, but it is not working. It throws some runtime exceptions.
有什么解决办法吗?
推荐答案
有几种方法可以实现您想要的效果,具体取决于具体情况.
There are a couple of ways to achieve what you want, depending on the circumstances.
最常见的情况(这就是您的情况)是使用子 Activity 获取用户输入时 - 例如从列表中选择联系人或在对话框中输入数据.在这种情况下,您应该使用 startActivityForResult
启动您的子活动.
The most common scenario (which is what yours sounds like) is when a child Activity is used to get user input - such as choosing a contact from a list or entering data in a dialog box. In this case you should use startActivityForResult
to launch your child Activity.
这提供了使用setResult
.setResult 方法接受一个 int 结果值和一个传递回调用 Activity 的 Intent.
This provides a pipeline for sending data back to the main Activity using setResult
. The setResult method takes an int result value and an Intent that is passed back to the calling Activity.
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
resultIntent.putExtra("some_key", "String data");
setResult(Activity.RESULT_OK, resultIntent);
finish();
要访问调用 Activity 中返回的数据,请覆盖 onActivityResult
.requestCode对应的是startActivityForResult
调用中传入的整数,而resultCode和数据Intent是从子Activity返回的.
To access the returned data in the calling Activity override onActivityResult
. The requestCode corresponds to the integer passed in in the startActivityForResult
call, while the resultCode and data Intent are returned from the child Activity.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (MY_CHILD_ACTIVITY) : {
if (resultCode == Activity.RESULT_OK) {
// TODO Extract the data returned from the child Activity.
String returnValue = data.getStringExtra("some_key");
}
break;
}
}
}
这篇关于将数据发送回 Android 中的 Main Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!