简体   繁体   English

如何将一个片段的引用传递给另一个片段

[英]How to pass reference of one fragment to another fragment

I want to call method in fragment from another fragment for which I made interface and implemented in fragment now I want to pass reference of fragment where i implemented method to another fragment next to it, how can I do that, I could have used constructor but fragment use new instance method and bundles. 我想从另一个片段中调用方法,该片段是我为其创建接口并在片段中实现的,现在我想将实现了方法的片段的引用传递给它旁边的另一个片段,我该怎么做,我本可以使用构造函数,但是片段使用新的实例方法和包。

Thanks 谢谢

Update I can call method by making instance of fragment but what is the best approach in terms of memory 更新我可以通过创建片段实例来调用方法,但是就内存而言最好的方法是什么

  1. Create interface. 创建界面。 Implement it by an activity 通过活动实施
  2. In sender fragment's constructor parametr receive instance of created interface from activity. 在发送方片段的构造函数中,parametr从活动接收已创建接口的实例。
  3. Pass boolean flag as interface's method parametr 传递布尔标志作为接口的方法参数
  4. As activity keeps boths links to sender and receiver fragments and as soon as activity get callback the activity fire needed method of receiver fragments. 当活动使发送者和接收者片段都保持链接时,一旦活动获得回调,活动就会触发接收者片段所需的方法。

Find some material in web like "passing data between two fragments". 在网上找到一些资料,例如“在两个片段之间传递数据”。 The idea is the same) 想法是一样的)

Let all your fragments have a callback to the activity. 让您的所有片段都具有对活动的回调。 Make an interface as below 制作如下界面

public interface Callback{
public void doSomething(params);
}

Now whenever you initialise the fragment, say FragmentClassA, in the FragmentClassA write a function setCallback as below, 现在,每当初始化片段时,例如FragmentClassA,在FragmentClassA中编写如下的setCallback函数,

private Callback callback;
public void setCallback(Callback callback){
this.callback=callback
}

In your activity, use the reference of the fragment to setCallback as below, 在您的活动中,使用片段的引用对setCallback进行如下操作,

fragmentAReference.setCallback(new Callback(){

    public void doSomething(params){
    //Now over here you can invoke fragmentB's reference to perform the job
    }
    });

So basically in order to invoke a function from fragment A to fragment B, fragment A invokes the callback of the activity and the activity uses the reference of fragmentB to invoke the required function 因此,基本上为了从片段A调用到片段B的功能,片段A会调用活动的回调,而活动使用fragmentB的引用来调用所需的功能

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

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