简体   繁体   English

属于两个不同活动的片段之间的通信

[英]Communication between fragments that belong to two different activities

I'm very new to Android development. 我对Android开发非常陌生。

I've made some researches to achieve passing data from Fragment A in Activity A to Fragment B in Activity B. Is that possible? 我已经进行了一些研究,以实现将数据从活动A中的片段A传递到活动B中的片段B。这可能吗?

All I could get from the tutorials on the internet is that we have to create an Interface that will be implemented by the parent Activity of two sibling fragments. 我可以从Internet上的教程中学到的就是,我们必须创建一个接口,该接口将由两个同级片段的父Activity来实现。 How to achieve it when the fragments belong to two different activities? 当片段属于两个不同的活动时如何实现? I'm stuck. 我被卡住了。

Thanks 谢谢

You would achieve it by implementing the said Interface and put the extras into the Intent for the Activity that has the other Fragment . 您可以通过实现上述接口并将附加内容放入具有另一个FragmentActivityIntent来实现。

Pseudo code could look like this 伪代码可能看起来像这样

Fragment A - calls interface methods on Activity A and passes data Fragment AActivity A上调用接口方法并传递数据

Activity A - calls startActivity with the extras inside the Intent Activity A调用startActivity并包含Intent

Activity B - got started and evaluates the said Intent and passes it to Fragment B Activity B开始并评估所述Intent并将其传递给Fragment B

Fragment B - receives the extras from Activity B Fragment BActivity B收取额外费用

you can use Intent to pass data between activity and from sibling fragment call method of activity like ((MainActivity).getActivity).methodSentData(String exampledata) and ((MainActivity).getActivity).methodGetData(); 您可以使用Intent在活动之间以及活动的同级片段调用方法之间传递数据,例如((MainActivity).getActivity).methodSentData(String exampledata)((MainActivity).getActivity).methodGetData(); to get data in the fragment. 在片段中获取数据。

methodSentData implements intent.putExtra("data",data); methodSentData实现intent.putExtra("data",data); to sent data to other activity and methodGetData() implements getintent().GetStringExtras("data"); 将数据发送到其他活动,并且methodGetData()实现getintent().GetStringExtras("data");

You can use local broadcast receiver. 您可以使用本地广播接收器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM