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
Difference Between ≫≫≫ and ≫≫
How to Mock Void Methods With Mockito
Android Listview Selected Item Stay Highlighted
How to Convert a Part of Java Source File to Kotlin
How to Set Java_Home Path on Ubuntu
Execute a Linux Terminal Command in Java
Create a New Folder Using Java Program on Windows and Linux MAChines
Is a Java Filelock a Posix Advisory (Fcntl) Lock
Why the Operating System Says It Can't Allocate Memory to Jvm When It Has Enough Memory
When to Use Generic Methods and When to Use Wild-Card
Failed to Load the Jni Shared Library (Jdk)
Maximum Length of Intent Putextra Method? (Force Close)
How to Set Addsnapshotlistener and Remove in Populateviewholder in Recyclerview Item
Firebase:Recycler View No Adater Attached , Skipping Layout
What's the Location of the Javafx Runtime Jar File, Jfxrt.Jar, on Linux