将数据发送回 Android 中的 Main Activity

编程入门 行业动态 更新时间:2024-10-27 06:25:33
本文介绍了将数据发送回 Android 中的 Main Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个活动:主要活动和子活动.当我按下主活动中的按钮时,子活动就会启动.

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

本文发布于:2023-11-11 11:08:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578257.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Android   Activity   Main

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!