How to get same childfragments(having recyclerview) instance in all the fragments of viewpager?

120 Views Asked by At

I am stuck in a situation where I have recyclerview with item data in it and I need to fetch same instance in all the fragments (three) of viewpager to operate on the same recyclerview.

What I have done :

I have made one separate fragment names as ItemListFragment with common buttons and option in the list and now trying to add it as child fragment to my viewpager fragments. I can add them as child fragment but at this point I have to create 3 different ItemListFragment for all the PrentFragments.

Kindly help me to overcome this situation or suggest any other way for using common recyclerlist in all the 3 fragments. I have searched stackoverflow but nothing is of any help.

Here is the image to get an idea about the situation:

enter image description here

1

There are 1 best solutions below

1
On

You can try using global static reference technique in this case.

Declare your childview in Application class ( a class which extends Application class of Android).

public class AppController extends Application{
  public static final String LOG_TAG = ApplicationController.class
        .getSimpleName();

  // Application Instance
  private static ApplicationController applicationController = null;

  public static ListView childview;
  public static ChildAdapter childAdapter;

   @Override
   public void onCreate() {
    super.onCreate();
    applicationController = this;
   }
}

Now in any of your Fragment suppose Fragment A,check global object of childFragment whether its null or not,if its null initilize it normally like other chilfragments,since its reference is global the varibale in AppController now contains the instance of childfragment.

Now in Fragment B check whether global reference null or not,since you initialized it in Fragment A you will not get null,now attach childFragment to Fragment B like normal childfragments