How do I open a new fragment from another fragment?
Add following code in your click listener function,
NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag, "findThisFragment")
.addToBackStack(null)
.commit();
The string "findThisFragment"
can be used to find the fragment later, if you need.
You should create a function inside activity to open new fragment and pass the activity reference to the fragment and on some event inside fragment call this function.
This is more described code of @Narendra's code,
First you need an instance of the 2nd fragment. Then you should have objects of FragmentManager and FragmentTransaction. The complete code is as below,
Fragment2 fragment2=new Fragment2();
FragmentManager fragmentManager=getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_main,fragment2,"tag");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Hope this will work. In case you use androidx, you need getSupportFragmentManager() instead of getFragmentManager().