-1

So I have a Fragment(A) with a ListView. If I click the Listview's item, then I want to open another Fragment(B). My only problem is, that when I open the B Fragment, also the A is appear in the layout.

FragmentA nextFrag = new FragmentA(data);
getFragmentManager().beginTransaction()
    .replace(R.id.fragment_a_layout, nextFrag)
    .commit();

What is the proper way to open a new Fragment, without show the previuos one too?

@sweak So I understand, that I need an interface, which I already write in my FragmentA class:

public interface FragmentListener {
    void replaceFragments();
}

Then I implement this interface in my MainActivity.class, if I am right.

@Override
public void replaceFragments() {
    FragmentB nextFrag = new FragmentB();
            getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_layout, nextFrag)
        .commit();
}

In my FragmantA onClickListener, I call this method: (FragmentListener listener)

 listener.replaceFragments(recipeForFragment);

But now my problem is that my listener is null, so somehow I need to initializte, but I don't know how. Maybe I create a setter for it, in the FragmentA:

public void setFragmentListener(FragmentListener fragmentListener) {
    this.listener = fragmentListener;
}

But where should I call this setter and when?

Cam
  • 61
  • 6
  • 1
    The activity should be replacing the fragments, not the fragment itself - let the `FragmentA` notify the activity to replace the fragments. You can do it via the `interface` defined in the `FragmentA` – sweak Aug 31 '22 at 14:50
  • Does this answer your question? [How do I open a new fragment from another fragment?](https://stackoverflow.com/questions/21028786/how-do-i-open-a-new-fragment-from-another-fragment) – gioravered Aug 31 '22 at 15:00

1 Answers1

-1

The existing answers are surprisingly incorrect.

If you have androidx.fragment:fragment-ktx:x.x.x (can't remember the latest version), you can do:

supportFragmentManager.commit {
    replace(R.id.fragment_a_layout, nextFrag, "Some Tag If You need")
    addToBackStack(null) // optional
}

Or even

supportFragmentManager.commit {
    replace(R.id.fragment_a_layout, YourFragment::class.java)
}

In this way you don't even need those silly YourFragment.newInstance() methods, as the 3rd (optional) parameter is a Bundle for your args.

I'm sure there's a Java equivalent.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144