Search code examples
javaandroidandroid-fragmentsdeprecated

How to call a method of a Fragment from another Fragment?


How can I call a method of a Fragment from a DialogFragment, knowing that TargetFragment is now deprecated?

In the past, I could do it this way:

ParentFragment

DialogFragment dialog = new DialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(this.getSupportFragmentManager(), "tag");

DialogFragment

((ParentFragment) this.getTargetFragment()).myMethod();

This is no longer possible, because TargetFragment is now deprecated.

I read that I can use setFragmentResultListener() to pass variables, but how can I call the ParentFragment.myMethod() method from the DialogFragment?


Solution

  • Here is the solution I found.

    ParentFragment

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getParentFragmentManager().setFragmentResultListener("result", this, new FragmentResultListener() {
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                String action = bundle.getString("action");
                if (action != null)
                    if (action.equals("myMethod"))
                        ParentFragment.this.myMethod();
            }
        });
    }
    

    DialogFragment

    Bundle result = new Bundle();
    result.putString("action", "myMethod");
    this.getParentFragmentManager().setFragmentResult("result", result);