简体   繁体   中英

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.
  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,

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

In your activity, use the reference of the fragment to setCallback as below,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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