Hultan
Hultan

Reputation: 1549

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

Upvotes: 97

Views: 195518

Answers (14)

Lehrian
Lehrian

Reputation: 343

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

Upvotes: 3

Muhammad Rizwan
Muhammad Rizwan

Reputation: 37

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

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

Upvotes: 2

Akanksha Bhardwaj
Akanksha Bhardwaj

Reputation: 11

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

Upvotes: 1

Aathil Ahamed
Aathil Ahamed

Reputation: 474

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

Upvotes: 0

Jatin
Jatin

Reputation: 27

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

Upvotes: 0

All Іѕ Vаиітy
All Іѕ Vаиітy

Reputation: 26372

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

Upvotes: 2

Nipuna Dilhara
Nipuna Dilhara

Reputation: 424

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

Upvotes: 12

Maris S.
Maris S.

Reputation: 61

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.

Upvotes: 2

Gerry R
Gerry R

Reputation: 402

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

Upvotes: 0

Parinda Rajapaksha
Parinda Rajapaksha

Reputation: 3109

Use this,

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

Upvotes: 6

vipul mittal
vipul mittal

Reputation: 17401

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.

Upvotes: 5

Narendra
Narendra

Reputation: 1844

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.

Upvotes: 178

Mbanda
Mbanda

Reputation: 1018

 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.

Upvotes: 0

Vinod Joshi
Vinod Joshi

Reputation: 7852

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

Upvotes: 2

Related Questions