How do I open a new fragment from another fragment?

AndroidAndroid FragmentsOnclicklistenerAndroid Button

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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

Solution 3 - Android

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.

Solution 4 - Android

Use this,

AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();

Solution 5 - Android

@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();	
}

Solution 6 - Android

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

Solution 7 - Android

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)
        }

Solution 8 - Android

 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.

Solution 9 - Android

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

Solution 10 - Android

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.

Solution 11 - Android

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

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/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();
      }
  });

Solution 12 - Android

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

Solution 13 - Android

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

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

Solution 14 - Android

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="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/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.

https://developer.android.com/guide/navigation/navigation-navigate

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHultanView Question on Stackoverflow
Solution 1 - AndroidNarendraView Answer on Stackoverflow
Solution 2 - AndroidNipuna DilharaView Answer on Stackoverflow
Solution 3 - Androidvipul mittalView Answer on Stackoverflow
Solution 4 - AndroidParinda RajapakshaView Answer on Stackoverflow
Solution 5 - AndroidVinod JoshiView Answer on Stackoverflow
Solution 6 - AndroidAll Іѕ VаиітyView Answer on Stackoverflow
Solution 7 - AndroidAkanksha BhardwajView Answer on Stackoverflow
Solution 8 - AndroidMbandaView Answer on Stackoverflow
Solution 9 - AndroidGerry RView Answer on Stackoverflow
Solution 10 - AndroidMaris S.View Answer on Stackoverflow
Solution 11 - AndroidJatinView Answer on Stackoverflow
Solution 12 - AndroidAathil AhamedView Answer on Stackoverflow
Solution 13 - AndroidMuhammad RizwanView Answer on Stackoverflow
Solution 14 - AndroidLehrianView Answer on Stackoverflow