How to replace the activity’s fragment from the fragment itself?

It’s actually easy to call the activity to replace the fragment.

You need to cast getActivity():

((MyActivity) getActivity())

Then you can call methods from MyActivity, for example:

((MyActivity) getActivity()).replaceFragments(Object... params);

Of course, this assumes you have a replaceFragments() method in your activity that handles the fragment replace process.

Edit: @ismailarilik added the possible code of replaceFragments in this code with the first comment below which was written by @silva96:

The code of replaceFragments could be:

public void replaceFragments(Class fragmentClass) {
    Fragment fragment = null;
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment)
            .commit();
}

Leave a Comment