1

I have two fragment Parent and child, And Now I am trying to get some value from childFragment to parentFragment using callback.

Here is what i have tried so far:

Adding childfragment

 activity.getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_layout, fragment).addToBackStack(null)
                .commit();

Now on buttonClick of childFragment i want to get response to parentFragment.

Example:

nearestCenter.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
           if (getFragmentManager() != null) {
        getFragmentManager().popBackStack();
    }
    }
});

P.S I know how to do with Activity to Fragment but is there any way to get callback from fragment to frag.

Bunny
  • 1,044
  • 12
  • 23
  • 1
    Use this already answered question https://stackoverflow.com/questions/23142956/sending-data-from-nested-fragments-to-parent-fragment – ahjo4321hsotuhsa Jun 21 '18 at 12:28

2 Answers2

3

You can use below code. Of course you should be careful about class cast exception and null pointer exception.

private void callParentFragmentMethod(){
    ParentFragment f = (ParentFragment) getParentFragment();
    f.someMethod();
}
toffor
  • 1,219
  • 1
  • 12
  • 21
-1

You can use interface to interact like this :

public interface MyInterface{
  void sendMessageToParent(Parameters parameter);
}

Now implement this on your parent fragment like this -

public class ParentFragment implements MyInterface{

  public static Myinterface myinterface;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     super.onCreateView(inflater, container, savedInstanceState);

     // Register your interface like this. 
     myinterface = this;

     return view;
}      

  @Override
  public void sendMessage(Parameters Parameters){

  }
}

Now from child activity call it like this:-

if(ParentFragment.myinterface!=null){
  ParentFragment.myinterface.sendMessageToParent(parameters);
}

This will do. And make sure in onDestroy of parent you assign it null like this:-

myinterface = null;

Hope this helps.

Sarthak Gandhi
  • 2,130
  • 1
  • 16
  • 23