How to replace a custom fragment with another fragment? - android

I know this question has been asked before in other threads like this one :
Trying to replace one fragment with another
But, in these cases the layout file would have a node with an id. In my case, I created a custom SettingsFragment and this SettingsFragment consists of many items. When I click on one item, it will start another fragment CreatePasswordFragment.
Now, my SettingsFragment does not have an id (or does it? I am a newbie to android....), so I don't know how to use .replace(R.id.fragment_container,CreatePasswordFragment.newInstance())
So far, I have used the following method, and while it works I am wondering if there is a better way to do it?
getActivity()
.getSupportFragmentManager()
.beginTransaction()
.remove(SettingsFragment.this)
.replace((android.R.id.content, CreatePasswordFragment.newInstance(userProfile.email))
.addToBackStack(null)
.commit();

The id in the replace() method is the container id, not your fragment id. So it would be the id of whatever layout in your activity is displaying the fragment. So you are doing it right. One thing to note, however, is that you do not need to call remove(). You can just call replace() and the FragmentManager will automatically call remove() for you.

Related

"Can't change container ID of fragment" when using "replace"

So I've found a few similar cases, but nothing about this specific case.
I have a FrameLayout which I gave the id "container", and contains a few different fragments.
In my code for the activity that contains that FrameLayout, I'm trying to switch between the fragments with a function that receives a fragment.
In that code:
a. I have defined private FragmentManager fm = getSupportFragmentManager();
b. I have defined FragmentTransaction ft; to use later.
c. My function is:
private void setActiveFragment(Fragment fragment){
//Determine which button should be marked as "active"
determineButtonByFragment(fragment);
//Repalce fragment
ft = fm.beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(String.valueOf(fragment.getId()));
ft.commit();
}
Any idea why i would get this error on the "replace"?
EDIT:
Ok, I just realized a bit more about fragments. Since all 5 fragments are added to the FrameLayout, the "replace" won't work. You get the "can't chance container ID error" when you're trying to move a fragment from 1 parent view to another (Or in this, case, to the same one), without detaching it first.
Let's say I have fragments A, B, C, D, E.
If I want to replace to fragment B right now, I won't be able to do it until I remove it from it's original parent (Or at least that's how I think it works. please enlighten me otherwise). The only question that remains now, is how do I switch between my fragments correctly...
Alright, apparently you cannot use the "replace" method on fragments which are hard-coded in the layout:
Replacing a fragment with another fragment inside activity group
What I have to do now, is inside the function, to find a way to determine the fragment I want to display, create a new instance of it, and use "replace" on it.

How can I get Fragment from View?

I added some Fragment into a TableLayout and I want to manage them from my container Activity, so I used this:
Fragment fragment = (Fragment) tableLayout.getChildAt(i);
but getChildAt(int) returns a View and a View could NOT cast to Fragment
I don't understand why people are down-voting your question. Fragments can be very confusing at times, especially for beginners. To understand your problem, you must learn what is a Fragment and how they are used.
To start with, a View is something that has an existence on the screen. Examples include: TextView, EditText, Button, etc. They are placed inside "layouts" written in Xml or Java/Kotlin. These layouts are shown using an Activity.
Now, a Fragment is not a View. It does not have any existence on the screen at all. Instead, it's a class that simply manages a "layout" — kinda similar to an Activity. If you need the View returned by your Fragment's onCreateView(), you can directly use findViewById() within your Activity.
If you need a reference to your Fragment, there are two possible ways of doing this:
1) If you added the Fragment programmatically like this
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container_viewgroup, myFragment, FRAGMENT_TAG)
.commit();
You can use:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
2) If you added the Fragment inside an XML layout like this:
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="#+id/fragmentContainer"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
You can use this:
getFragmentManager().findFragmentById(R.id.fragmentContainer);
Basically, each Activity has a FragmentManager class that maintains all the active Fragments, and there are two ways of finding them: Using a unique TAG that you pass while showing a fragment, or passing the container view-ID where the fragment was added.
For people looking how to actually get a reference to the Fragment object from a View there is now a method in FragmentManager called findFragment(View) (reference)
//in Java
FragmentManager.findFragment(view)
//in Kotlin there is an extension function
view.findFragment()
Be careful - it will throw an IllegalStateException if the view was not added via a fragments onCreateView.
You can not get a fragment like this. You will have to add fragment with a tag and retrieve it by that tag.
to add a fragment do following:
getFragmentManager().beginTransaction().add(R.id.container, fragment, "tagTofindFragment");
to get fragment:
fragment = getFragmentManager().findFragmentByTag("tagTofindFragment");
Here tagTofindFragment is that tag that should be unique among your fragments.

Android how to send data to a running fragment

is there a way to send some data from an activity to a running fragment?
In my app I'm adding a second fragment over another fragment. I intentionally use the add method instead of the replace method. So now I want to hide my second fragment with
fragmentManager.popBackStack();
and my first fragment reappears. After hiding the second fragment I want to send some data from my activity to the still running frist fragment.
Any idea how to do this? It doesn't work with bundles (put extra), because I don't rebuild the fragment, I just hide the second one!
one simple solution is:
MyFragment oldFragment = (MyFragment) fragmentManager.findFragmentById(R.id.fragment_place);
fragmentManager.popBackStackImmediate();
MyFragment newFragment = (MyFragment)fragmentManager.findFragmentById(R.id.fragment_place);
newFragment.postData(...);
You can use an EventBus library like this one, it's easy to use and very convenient.
You can use tags on the Fragments when you create them to call them when needed.
getFragmentManager().beginTransaction()
.add(R.id.content, new SomeFragment(), SomeFragment.class.getSimpleName())
.commit();
So above I use the simple name of the class to tag the fragment when I create and add it to the activity.
SomeFragment fragment = (SomeFragment) getFragmentManager().findFragmentByTag(SomeFragment.class.getSimpleName());
And I can call it back when I need it and know it is being displayed like above, now I can call send it data like normal by calling a public method in the custom fragment and passing it the data as a param.

How to add a Fragment ID or Fragment tag for a fragment in a ViewPager [duplicate]

How can I set a Fragment's Id so that I can use getSupportFragmentManager().findFragmentById(R.id.--)?
You can't set a fragment's ID programmatically.
There is however, a String tag that you can set inside the FragmentTransaction which can be used to uniquely identify a Fragment.
As Aleksey pointed out, you can pass an ID to FragmentTransaction's add(int, Fragment) method. However, this does not specify the ID for a Fragment. It specifies the ID of a ViewGroup to insert the Fragment into. This is not that useful for the purpose I expect you have, because it does not uniquely identify Fragments, but ViewGroups. These IDs are of containers that one or more fragments can be added to dynamically. Using such a method to identify Fragments would require you to add ViewGroups dynamically to the Layout for every Fragment you insert. That would be pretty cumbersome.
So if your question is how to create a unique identifier for a Fragment you're adding dynamically, the answer is to use FragmentTransaction's add(int containerViewId, Fragment fragment, String tag) method and FragmentManager's findFragmentByTag(String) method.
In one of my apps, I was forced to generate strings dynamically. But it's not that expensive relative to the actual FragmentTransaction, anyway.
Another advantage to the tag method is that it can identify a Fragment that isn't being added to the UI. See FragmentTransaction's add(Fragment, String) method. Fragments need not have Views! They can also be used to persist ephemeral state between config changes!
Turns out you may not need to know the fragment id.
From the docs:
public abstract Fragment findFragmentById (int id)
Finds a fragment that was identified by the given id either
when inflated from XML or as the container ID when added in
a transaction.
The important part is "as the container ID when added in a transaction".
so:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, new AwesomeFragment())
.commit();
and then
AwesomeFragment awesome = (AwesomeFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_holder);
will get you whatever (awesome) fragment is held in R.id.fragment_holder.
In most cases you can use the fragment tag as well as the ID.
You can set the tag value in FragmentTransaction.add(Fragment fragment, String tag );.
Then you can use the command FragmentManager.findFragmentByTag(String tab) to find the fragment in question.
As Tom and others already mention, there are ways to put a tag on a fragment and use that tag for identification. A subsequent problem I've come across with those solutions is that the fragment doesn't get a tag until it's associated with the Activity (or, actually, the FragmentManager). What to do if one needs to identify a fragment before it has been tagged?
My solutions so far all rely on the oldest (Java) trick in the world: create a minimalistic template fragment which takes an id in one of it's constructors and provides a getFragmentId() method which returns that id. I then let those fragments that need early identification extend that template and; voila! Problem solved.
This solution might, unfortunately, require a set of template fragments, one for each fragment type, ListFragment, DialogFragment or plain old Fragment (POFO?!) that need early identification. But this is manageable in the case of fragments I think, considering the gains provided.
Sorry for tearing up healing wounds :-)
Cheers!
Use the following:
To add a fragment:
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentToBeAdded, tag).commit();
To identify existing fragment:
getFragmentManager().findFragmentByTag(fragmentName);
When using a tag please do make sure to add the
fragmentTransaction.addToBackStack(null);
method so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.
If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.
You can find this at the end of this page.
I lost about 30 minutes trying to figure out why my Fragment was not being found through a simple findFragmentByTag(); call
In addition to Tom's answer, replace method also supports the fragment tag, in addition to add method.

Android - Set fragment id

How can I set a Fragment's Id so that I can use getSupportFragmentManager().findFragmentById(R.id.--)?
You can't set a fragment's ID programmatically.
There is however, a String tag that you can set inside the FragmentTransaction which can be used to uniquely identify a Fragment.
As Aleksey pointed out, you can pass an ID to FragmentTransaction's add(int, Fragment) method. However, this does not specify the ID for a Fragment. It specifies the ID of a ViewGroup to insert the Fragment into. This is not that useful for the purpose I expect you have, because it does not uniquely identify Fragments, but ViewGroups. These IDs are of containers that one or more fragments can be added to dynamically. Using such a method to identify Fragments would require you to add ViewGroups dynamically to the Layout for every Fragment you insert. That would be pretty cumbersome.
So if your question is how to create a unique identifier for a Fragment you're adding dynamically, the answer is to use FragmentTransaction's add(int containerViewId, Fragment fragment, String tag) method and FragmentManager's findFragmentByTag(String) method.
In one of my apps, I was forced to generate strings dynamically. But it's not that expensive relative to the actual FragmentTransaction, anyway.
Another advantage to the tag method is that it can identify a Fragment that isn't being added to the UI. See FragmentTransaction's add(Fragment, String) method. Fragments need not have Views! They can also be used to persist ephemeral state between config changes!
Turns out you may not need to know the fragment id.
From the docs:
public abstract Fragment findFragmentById (int id)
Finds a fragment that was identified by the given id either
when inflated from XML or as the container ID when added in
a transaction.
The important part is "as the container ID when added in a transaction".
so:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, new AwesomeFragment())
.commit();
and then
AwesomeFragment awesome = (AwesomeFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_holder);
will get you whatever (awesome) fragment is held in R.id.fragment_holder.
In most cases you can use the fragment tag as well as the ID.
You can set the tag value in FragmentTransaction.add(Fragment fragment, String tag );.
Then you can use the command FragmentManager.findFragmentByTag(String tab) to find the fragment in question.
As Tom and others already mention, there are ways to put a tag on a fragment and use that tag for identification. A subsequent problem I've come across with those solutions is that the fragment doesn't get a tag until it's associated with the Activity (or, actually, the FragmentManager). What to do if one needs to identify a fragment before it has been tagged?
My solutions so far all rely on the oldest (Java) trick in the world: create a minimalistic template fragment which takes an id in one of it's constructors and provides a getFragmentId() method which returns that id. I then let those fragments that need early identification extend that template and; voila! Problem solved.
This solution might, unfortunately, require a set of template fragments, one for each fragment type, ListFragment, DialogFragment or plain old Fragment (POFO?!) that need early identification. But this is manageable in the case of fragments I think, considering the gains provided.
Sorry for tearing up healing wounds :-)
Cheers!
Use the following:
To add a fragment:
getFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentToBeAdded, tag).commit();
To identify existing fragment:
getFragmentManager().findFragmentByTag(fragmentName);
When using a tag please do make sure to add the
fragmentTransaction.addToBackStack(null);
method so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.
If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.
You can find this at the end of this page.
I lost about 30 minutes trying to figure out why my Fragment was not being found through a simple findFragmentByTag(); call
In addition to Tom's answer, replace method also supports the fragment tag, in addition to add method.

Categories

Resources