How do I open a new fragment from another fragment? - android

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

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.

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

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.

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

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

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

use this in adapter/fragment all previous methouds are expired now
((AppCompatActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.container,new cartFragment()).commit();

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

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

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

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

Related

How to replace fragment from ViewPager with a new one

I found so many similar questions and so many different answers, but none of them helped me. I will try to post a clear question to get a clear answer if it's possible.
So I have an Activity that has a ViewPager with FragmentStatePagerAdapter containing (for now) only one fragment (HomeScreenFragment).
Inside HomeScreenFragment I have a RecyclerView with a list of several kind of different icons which should open a different fragment for each item click.
HomeScreenFragment has a FrameLayout as a root layout with id name "container". This is the method I'm calling to replace HomeScreenFragment with MainTypesFragment in this case:
private void openAllTypesFragment() {
MainTypesFragment fragment = new MainTypesFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(HomeScreenFragment.class.getName());
transaction.commit();
eventBus.post(new Event(null, Event.EVENT_FRAGMENT));
}
Since FragmentStatePagerAdapter is initialized in MainActivity, I'm sending an event which will MainActivity catch and call adapter.notifyDataSetChanged();
Doing it this way, nothing happens.. I tried with getChildFragmentManager() instead of getActivity().getSupportFragmentManager() and in that case, previous fragment (HomeScreenFragment) is visible underneath new one (MainTypesFragment)..
Any ideas what am I doing wrong here?
The container you are using is wrong.Maintain one container in the activity xml and use that container to load all the fragments.
transaction.replace(R.id.container, fragment);
The container here is to be the activity container in which viewpager and other views should be present.
You can try my code :
private void addFilmDetailFragment(Movie movie){
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FilmDetailFragment fragment = new FilmDetailFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("movie", movie); // Key, value
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.mainContentStore, fragment);
// fragmentTransaction.replace(R.id.mainContent, fragment, Config.TAG_FILM_DETAIL);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
In a fragment of viewpager :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContentStore"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerFilm"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
It worked for me, i hope it will help your problem!
You need container inside activity for ViewPager and inside fragments(pages), containers for opening new fragments inside pages.
And if you want to open new fragment you should user something like this
in page fragment
getChildFragmentManager().beginTransaction()
.replace(R.id.page_fragment_container, fragment)
.addToBackStack(name)
.commit()
where R.id.page_fragment_container container inside page fragment.

How to start a fragment from another activity

I want to start a fragment from B activity but the fragment is in main activity. If I use FragmentTransaction, but it gives error "No view found for ID for fragment"
Code
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();
Error
No view found for id 0x7f0e00be (com.company.app:id/layoutContent) for fragment PlaylistFrag{5764566 #0 id=0x7f0e00be}
If I understand your question, You want to start a fragment in an Activity from another Activity.
This is what I do to get Around that.
From the current Activity, I would start the other Activity on Click
Intent intent = new Intent (ActivityA.this, ActivityB.class);
intent.putExtra("EXTRA", "openFragment");
startActivity(intent);
In the destination Activity, listen for intent extras and start action.
switch (getIntent().getStringExtra("EXTRA")){
case "openFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.replacableLayout, new FragmentActivityB()).commit();
getSupportActionBar().setTitle("Fragment Activity B");
break;
}
It works for me...
this will fire an exception as getSupportFragmentManager() is a function with the Activity you work on it so when you use ft.replace(R.id.layoutContent, frag); will look for layoutContent on current activity and will not found
i don't how u want to
Solution ==> - use Event Bus or Rxjava :) or may use a n interface with setter and getter and check it in another activity or use static variable to check the fragment you want to replaced to :)
Add this code in your onClick
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
and add onBackPressed()
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Make Layout like below in MainActivity.java and its layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/activity_add_workout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nujster.activity.AddWorkoutActivity">
<LinearLayout
android:id="#+id/add_workout_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
</RelativeLayout>
Then, in main activity write below code to call fragment
public class AddWorkoutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
getSupportFragmentManager().beginTransaction().add(R.id.add_workout_fragment, new LevelFragment(), "levels").addToBackStack(null).commit();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("levels") != null) {
LevelFragment levelFragment = (LevelFragment) getSupportFragmentManager().findFragmentByTag("levels");
if (levelFragment.isVisible()){
finish();
} else{
getSupportFragmentManager().popBackStack();
}
}
}
}
You can load same fragment in different activities.
Usually Fragment loads in Activity container.
Activity-1 layout have a container say R.id.layoutContent
Activity-2 layout also should have a container R.id.xxx
ft.replace(R.id.layoutContent[Container where fragment loads], frag);
May be Activity-2 do not have id of container

replacing fragments in android studio

I need help with code snippet for replacing a fragment with another fragment on click of a button.
Here is the XML for the MainActivity
What can i do to resolve this error?
Tried searching the web only to come up with the same solution.
If somebody could please help me out on this.
Code for Main.Activity
public class MainActivity extends AppCompatActivity{
Button button1, button2, button3, button4;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.layout1);
button2=(Button)findViewById(R.id.layout2);
button3=(Button)findViewById(R.id.layout3);
button4=(Button)findViewById(R.id.layout4);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frag, fragment);
transaction.commit();
}
});
I saw few issues in your code:
If you add your fragment inside xml file, you cant remove/replace it in the future. As described from Google Page:
Note: When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot remove the fragment at runtime. If you plan to swap your fragments in and out during user interaction, you must add the fragment to the activity when the activity first starts, as shown in the next lesson.
Your error may come from casting fragment. You should check your Fragment2. it maybe a support fragment.
Update
Here's the link to learning more about creating/adding fragment: Google Guide
Based on your comments, you should check what you did import in the Fragment2 layout (import android.support.v4.app.Fragment; or not). Are all your fragments from the same package or not?
The variable 'fragment' is an object of class Fragment and you are creating it as a object of class Fragment2 (which is a subclass of Fragment). This is not valid hence it's showing an error. Also to replace any fragment the fragment it should be inside a container view (usually a FrameLayout) and then you can use the replace transaction to replace it on the button click. The code should be as follows:
XML Code:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="frameLayout" />
Java Code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frameLayout,fragment2).commit();
}
});
Just replace your fragment in your xml with a FrameLayout.
Now within button's onClickListener
YourFragment fragment = YourFragment.getInstance();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frLayout, fragment, "TAG");
transaction.commit();
Hope that helps.
You should try
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in xml insted of fragment
and try this
Fragment2 frag2 = new Fragment2();
getSupportFragmentManager().beginTransaction().replace(R.id.frag, frag2);
in java code.

Call a Fragment from an Activity (from OnClickListener)

I have a button inside my Activity and when I click on this button I want to call a Fragment.
For example if I want to call an Activity I can use the intent but if I want to call a Fragment, how can I do that?
I have checked other questions but I have not found an answer to what I'm asking.
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
What am I going to put inside this?
You can add your fragment dynamically.You want to create a fragment.
To programmatically add or remove a Fragment, you will need the FragmentManager and FragmentTransaction
XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/myFrame" <!-- Id which you're gonna use in Java -->
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me" />
</LinearLayout>
Java
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
MyFragment myfragment = new MyFragment(); //your fragment
// work here to add, remove, etc
fragmentTransaction.add (R.id.myFrame, myfragment);
fragmentTransaction.commit ();
}
});
See this doc
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.
The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
https://developer.android.com/guide/components/fragments.html#Transactions
Quotation

Fragment shared element transition with add() instead of replace()?

I am trying to make a shared element transition between fragments, everything works fine when using replace() to add the second fragment, however in the codebase add() is used a lot, but when using that, transition just skips to end values
Is it possible to have the transition between added fragments?
Thanks
#Override
public void onClick(View v) {
setSharedElementReturnTransition(TransitionInflater.from(getActivity())
.inflateTransition(android.R.transition.move));
FragmentB secondFragment = new FragmentB();
secondFragment.setSharedElementEnterTransition(TransitionInflater.from(getActivity())
.inflateTransition(android.R.transition.move));
getFragmentManager().beginTransaction()
.add(R.id.container, secondFragment)
.addToBackStack(null)
.addSharedElement(imageView, imageView.getTransitionName())
.commit();
}
Try this
getSupportFragmentManager().beginTransaction()
.addSharedElement(myImage, "mytransition")
.add(R.id.recycler_view_container, myFragment2)
.hide(myFragment1)
commit();
worked for me
since the system isnt going through the onPause from the first fragment its not going to happen. becuase when you add a new fragment, the new fragment comes on the top of the old fragment.
but you can fake it though you will have more code !
there is a sample below:
https://github.com/Kisty/FragmentTransitionExample
and a video not compeletely related but helps you to get the idea:
https://www.youtube.com/watch?v=CPxkoe2MraA
Try add .detach() method for FragmentTransaction.
FragmentManager manager = activity.getSupportFragmentManager ();
Fragment currentFragment = manager.findFragmentById (CONTAINER_ID);
int intoContainerId = currentFragment.getId ();
manager.beginTransaction ()
.setTransition (FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addSharedElement(view, transitionName)
.addToBackStack (withTag)
.detach(currentFragment)
.add(intoContainerId, newFragment, withTag)
.commit();

Categories

Resources