在Android的数据发送回主要活动数据、Android

2023-09-11 11:05:44 作者:╰情場guàn犭

我有两个活动。主要活动和儿童活动。 当我preSS按钮,儿童活动启动 现在,我没有问题。我想送一些数据 返回到主屏幕。我使用的包类 但它不工作。它抛出一些运行时异常 有没有什么解决办法吗?任何人都知道答案,请 告诉我吧。

I have two activities. Main activity and child activity. When I press a button, the child activity is launched Now I have no problem. I want to send some data back to the main screen. I used The Bundle class but it is not working. It throw some run time exception Is there any solution? Anyone knows the answer please tell me.

推荐答案

有几种方法来达到你想要的,视情况而定。

There are a couple of ways to achieve what you want, depending on the circumstances.

最常见的情况(这是你的声音等),当一个子活动是用来获取用户输入 - 如选择从列表中的联系人,或在对话框中输入数据。在这种情况下,你应该使用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结果值和传递回调用活动的意图。

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.
setResult(Activity.RESULT_OK, resultIntent);
finish();

要访问返回的数据在调用活动覆盖 onActivityResult 。请求code对应于 startActivityForResult 呼叫传入的整数,而结果code和数据的意图是从孩子的活动返回。

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.
      }
      break;
    } 
  }
}