Replacing a Fragment with Another Fragment Inside Activity Group

Android replace the current fragment with another fragment

Then provided your button is showing and the click event is being fired you can call the following in your click event:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag");
ft.commit();

and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.

ft.addToBackStack(null);

Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.

How to replace fragment with another fragment?

As @RishabhDuttSharma suggested, Use a FrameLayout instead of fragment in your activity layout and initialize the first fragment in code.

Layout:

<FrameLayout
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Code:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Fragment fr = new FragmentOne();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}

Replacing a fragment from inside a fragment

Fragments are part of the Activity and fragment should be hosted through their parent activities as stated by google in Android developers docs.
You can refer this link:-
https://developer.android.com/training/basics/fragments/communicating

Invoking a fragment from another fragment and then replacing its layout

To get fragmentManger in fragment use

getActivity().getSupportFragmentManager()

As mentioned You should use R.id.flContent as your frame layout host so use

fragmentTransaction.replace(R.id.flContent, f1);

instead of

fragmentTransaction.replace(R.id.tableLayout1, f1); 


Related Topics



Leave a reply



Submit