How do I open a new fragment from another fragment?

I tried making a navigation between fragments. I've got the NewFragment.java with the new fragment working. My problem is:

How do I make this onClickListener run NewFragment.java correctly?

button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getActivity(), NewFragment.class); startActivity(i); }
});

FYI: This is from inside a fragment (I don't know if that matters).

1

14 Answers

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.

8

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().

2

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.

1

Use this,

AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
1
@Override
public void onListItemClick(ListView l, View v, int pos, long id) { super.onListItemClick(l, v, pos, id); UserResult nextFrag= new UserResult(); this.getFragmentManager().beginTransaction() .replace(R.id.content_frame, nextFrag, null) .addToBackStack(null) .commit();
}
1

Using Kotlin to replace a Fragment with another to the container , you can do

button.setOnClickListener { activity!! .supportFragmentManager .beginTransaction() .replace(R.id.container, NewFragment.newInstance()) .commitNow()
}

a simple option is to navigate to the second fragment by defining an action in the nav_graph.xml and then use it like this (example for Kotlin):

rootViewOfFirstFragment.someBtn.setOnClickListener{ Navigation.findNavController(rootViewOfFirstFragment) .navigate(R.id.action_firstFragment_to_secondFragment) }
 Fragment fr = new Fragment_class(); FragmentManager fm = getFragmentManager(); FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.add(R.id.viewpagerId, fr); fragmentTransaction.commit();

Just to be precise, R.id.viewpagerId is cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.

Adding to @Narendra solution...

IMPORTANT: When working with fragments, navigations is closely related to host acivity so, you can't justo jump from fragment to fragment without implement that fragment class in host Activity.

Sample:

public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {

Also, check your host activity has the next override function:

@Override public void onFragmentInteraction(Uri uri) {}Hope this helps...

Well my problem was that i used the code from the answer, which is checked as a solution here, but after the replacement was executed, the first layer was still visible and functionating under just opened fragment. My solution was simmple, i added

.remove(CourseListFragment.this)

the CourseListFragment is a class file for the fragment i tried to close. (MainActivity.java, but for specific section (navigation drawer fragment), if it makes more sense to you) so my code looks like this now :

LecturesFragment nextFrag= new LecturesFragment(); getActivity().getSupportFragmentManager().beginTransaction() .remove(CourseListFragment.this) .replace(((ViewGroup)getView().getParent()).getId(), nextFrag, "findThisFragment") .addToBackStack(null) .commit();

And it works like a charm for me.

first of all, give set an ID for your Fragment layout e.g:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""
xmlns:app=""
xmlns:tools=""
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:id="@+id/cameraFragment"**
tools:context=".CameraFragment">

and use that ID to replace the view with another fragment.java file. e.g

 ivGallary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UploadDoc uploadDoc= new UploadDoc(); (getActivity()).getSupportFragmentManager().beginTransaction() .replace(**R.id.cameraFragment**, uploadDoc, "findThisFragment") .addToBackStack(null) .commit(); } });

For Kotlin simply you can use this,

First: Create new instance of the fragment

val newFragment = NewFragment.newInstance()

Second: Start the fragment transaction

val fragmentTransaction: FragmentTransaction = activity!!.supportFragmentManager.beginTransaction()

Third: Replace current fragment with new fragment ( tips: avoid using id of the container view like R.id.fl_fragment, you may face view not find error, just use is at mentioned below)

fragmentTransaction.replace( (view!!.parent as ViewGroup).id,newFragment
)

Final Steps:

fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()

use this in adapter/fragment all previous methouds are expired now

((AppCompatActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.container,new cartFragment()).commit();

My how things do change in 8 years time. If you are using NavigationController in your app this is very simple. In your mobile_navigation.xml file you need to create "from" and "to" fragments. In the "from" fragment add the destination id of the "to" fragment.

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="" xmlns:app="" xmlns:tools="" android:id="@+id/mobile_navigation" app:startDestination="@+id/nav_home"> <fragment android:id="@+id/nav_home" android:name="com.yourpackage.FromFragment" android:label="@string/menu_home" tools:layout="@layout/from_fragment" > <action android:id="@+id/action_go" app:destination="@id/dest_fragment" app:enterAnim="@anim/nav_default_enter_anim" app:exitAnim="@anim/nav_default_exit_anim" app:popEnterAnim="@anim/nav_default_pop_enter_anim" app:popExitAnim="@anim/nav_default_pop_exit_anim"/> </fragment> <fragment android:id="@+id/dest_fragment" android:name="com.yourpackage.ToFragment" android:label="To Fragment" tools:layout="@layout/to_fragment" />
</navigation>

Then in your onClick handler call:

Navigation.findNavController(view).navigate(R.id.action_go);

This page provides more details including how to set up the destination programmatically.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like