当前位置: 首页 > 知识库问答 >
问题:

将数据从活动 a 传递到活动 b,然后再传递回活动 a

荣晨朗
2023-03-14

我想问一下如何将值从片段a传递到活动B,然后再传递回片段。我尝试使用bundle来传递值,但是它会给出错误的数据。

非常感谢。

共有1个答案

鲜于凯歌
2023-03-14

如果要将数据从活动B发送到活动A,请使用代码

在活动B中

Intent intent = new Intent ();
intent.putExtra ("string_1", "hello");
intent.putExtra ("string_2", "world");
intent.putExtra ("int_1", 1000);
intent.putExtra ("long_1", 2000l);
activity.setResult (Activity.RESULT_OK, intent);
finish()

因此,在活动 A 代码中将是

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
    if (resultCode == Activity.RESULT_OK)
    {
        String string_1 = intent.getStringExtra ("string_1", "");
        String string_2 = intent.getStringExtra ("string_2", "");
        int int_1 = intent.getIntExtra ("int_1", 0);
        long long_1 = intent.getLongExtra ("long_1", 0);
    }
}

所以现在你得到了A中的数据。所以通过使用片段中定义的方法,你可以将数据发送到目标片段

比如说

在片段中,如果您定义

public void refreshFragment(String s1)  {

// here s1 will be the data you send from activity Q
}

希望这有所帮助

 类似资料: