Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 211
Hultan Avatar asked Jan 09 '14 18:01

Hultan


People also ask

How do I start a new fragment from a fragment?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();

What is the process of starting a new fragment?

Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Right-click on the First button inside java, then click on New. Step 2: Then Go to Fragment. Step 3: (The next step is to choose the Fragment type.


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

like image 199
Narendra Avatar answered Oct 07 '22 23:10

Narendra