get the latest fragment in backstack
up vote
84
down vote
favorite
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?
FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();
/****After add , replace fragments
(some of the fragments are add to backstack , some are not)***/
//HERE, How can I get the latest added fragment from backstack ??
android android-fragments back-stack
add a comment |
up vote
84
down vote
favorite
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?
FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();
/****After add , replace fragments
(some of the fragments are add to backstack , some are not)***/
//HERE, How can I get the latest added fragment from backstack ??
android android-fragments back-stack
add a comment |
up vote
84
down vote
favorite
up vote
84
down vote
favorite
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?
FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();
/****After add , replace fragments
(some of the fragments are add to backstack , some are not)***/
//HERE, How can I get the latest added fragment from backstack ??
android android-fragments back-stack
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?
FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();
/****After add , replace fragments
(some of the fragments are add to backstack , some are not)***/
//HERE, How can I get the latest added fragment from backstack ??
android android-fragments back-stack
android android-fragments back-stack
edited Mar 30 '12 at 8:39
a.ch.
6,65632845
6,65632845
asked Mar 14 '12 at 12:43
Leem.fin
13.6k48131224
13.6k48131224
add a comment |
add a comment |
13 Answers
13
active
oldest
votes
up vote
138
down vote
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
20
in order to find fragment by tag it must be added/replaced with same tag.FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
orFragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc
– Saqib
Aug 1 '13 at 18:38
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
What's the point of calling it astack
if I can't access the fragment via a pop method?
– Kenneth Worden
Mar 20 '15 at 19:45
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
|
show 7 more comments
up vote
44
down vote
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
add a comment |
up vote
34
down vote
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
protected int getFragmentCount() {
return getSupportFragmentManager().getBackStackEntryCount();
}
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
Finally, you can find any of your fragments in your backstack with this method:
private Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
protected Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount() - 1);
}
Hope this helps!
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
add a comment |
up vote
5
down vote
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
public Fragment getTopFragment() {
List<Fragment> fragentList = fragmentManager.getFragments();
Fragment top = null;
for (int i = fragentList.size() -1; i>=0 ; i--) {
top = (Fragment) fragentList.get(i);
if (top != null) {
return top;
}
}
return top;
}
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
add a comment |
up vote
4
down vote
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
add a comment |
up vote
3
down vote
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
int lastFragmentCount = getBackStackEntryCount() - 1;
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
|
show 4 more comments
up vote
3
down vote
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
add a comment |
up vote
2
down vote
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
add a comment |
up vote
1
down vote
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager
and its backstack. Here's how you can do it:
public class FragmentStackManager {
private final FragmentManager fragmentManager;
private final int containerId;
private final List<Fragment> fragments = new ArrayList<>();
public FragmentStackManager(final FragmentManager fragmentManager,
final int containerId) {
this.fragmentManager = fragmentManager;
this.containerId = containerId;
}
public Parcelable saveState() {
final Bundle state = new Bundle(fragments.size());
for (int i = 0, count = fragments.size(); i < count; ++i) {
fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
}
return state;
}
public void restoreState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
int index = 0;
while (true) {
final Fragment fragment =
fragmentManager.getFragment(bundle, Integer.toString(index));
if (fragment == null) {
break;
}
fragments.add(fragment);
index += 1;
}
}
}
public void replace(final Fragment fragment) {
fragmentManager.popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.clear();
fragments.add(fragment);
}
public void push(final Fragment fragment) {
fragmentManager
.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.add(fragment);
}
public boolean pop() {
if (isEmpty()) {
return false;
}
fragmentManager.popBackStackImmediate();
fragments.remove(fragments.size() - 1);
return true;
}
public boolean isEmpty() {
return fragments.isEmpty();
}
public int size() {
return fragments.size();
}
public Fragment getFragment(final int index) {
return fragments.get(index);
}
}
Now instead of adding and removing fragments by calling FragmentManager
directly, you should use push()
, replace()
, and pop()
methods of FragmentStackManager
. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1)
.
But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
final List<Fragment> fragments = fragmentManager.getFragments();
final List<Fragment> topFragments = new ArrayList<>();
for (final Fragment fragment : fragments) {
if (fragment != null && fragment.isResumed()) {
topFragments.add(fragment);
}
}
return topFragments;
}
}
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack
has been called:
package android.support.v4.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
if (fragmentManager.getBackStackEntryCount() == 0) {
return Collections.emptyList();
}
final List<Fragment> fragments = new ArrayList<>();
final int count = fragmentManager.getBackStackEntryCount();
final BackStackRecord record =
(BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
BackStackRecord.Op op = record.mHead;
while (op != null) {
switch (op.cmd) {
case BackStackRecord.OP_ADD:
case BackStackRecord.OP_REPLACE:
case BackStackRecord.OP_SHOW:
case BackStackRecord.OP_ATTACH:
fragments.add(op.fragment);
}
op = op.next;
}
return fragments;
}
}
Please notice that in this case you have to put this class into android.support.v4.app
package.
add a comment |
up vote
1
down vote
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
fun getTopFragment(): Fragment? {
supportFragmentManager.run {
return when (backStackEntryCount) {
0 -> null
else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
}
}
}
*This should be called from inside an Activity.
Enjoy :)
add a comment |
up vote
0
down vote
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
add a comment |
up vote
0
down vote
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
add a comment |
up vote
0
down vote
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
add a comment |
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
138
down vote
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
20
in order to find fragment by tag it must be added/replaced with same tag.FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
orFragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc
– Saqib
Aug 1 '13 at 18:38
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
What's the point of calling it astack
if I can't access the fragment via a pop method?
– Kenneth Worden
Mar 20 '15 at 19:45
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
|
show 7 more comments
up vote
138
down vote
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
20
in order to find fragment by tag it must be added/replaced with same tag.FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
orFragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc
– Saqib
Aug 1 '13 at 18:38
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
What's the point of calling it astack
if I can't access the fragment via a pop method?
– Kenneth Worden
Mar 20 '15 at 19:45
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
|
show 7 more comments
up vote
138
down vote
up vote
138
down vote
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
edited Aug 21 '16 at 19:27
Ahmad
45.5k1590120
45.5k1590120
answered Mar 20 '12 at 13:38
Deepak Goel
3,78543347
3,78543347
20
in order to find fragment by tag it must be added/replaced with same tag.FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
orFragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc
– Saqib
Aug 1 '13 at 18:38
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
What's the point of calling it astack
if I can't access the fragment via a pop method?
– Kenneth Worden
Mar 20 '15 at 19:45
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
|
show 7 more comments
20
in order to find fragment by tag it must be added/replaced with same tag.FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
orFragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc
– Saqib
Aug 1 '13 at 18:38
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
What's the point of calling it astack
if I can't access the fragment via a pop method?
– Kenneth Worden
Mar 20 '15 at 19:45
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
20
20
in order to find fragment by tag it must be added/replaced with same tag.
FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
or FragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc– Saqib
Aug 1 '13 at 18:38
in order to find fragment by tag it must be added/replaced with same tag.
FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
or FragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
doc– Saqib
Aug 1 '13 at 18:38
3
3
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
The problem with this is if you have a fragment in the back stack twice, you can't retrieve a specific fragment when all you have is the index or backstackentry entity.
– Justin
May 29 '14 at 15:54
11
11
What's the point of calling it a
stack
if I can't access the fragment via a pop method?– Kenneth Worden
Mar 20 '15 at 19:45
What's the point of calling it a
stack
if I can't access the fragment via a pop method?– Kenneth Worden
Mar 20 '15 at 19:45
5
5
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
RTFM: developer.android.com/reference/android/app/…
– artkoenig
Apr 5 '15 at 10:04
3
3
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
This returns null
– TeodorKolev
Jul 29 '16 at 8:59
|
show 7 more comments
up vote
44
down vote
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
add a comment |
up vote
44
down vote
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
add a comment |
up vote
44
down vote
up vote
44
down vote
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
FragmentManager.findFragmentById(fragmentsContainerId)
function returns link to top Fragment
in backstack. Usage example:
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment fr = fragmentManager.findFragmentById(R.id.fragmentsContainer);
if(fr!=null){
Log.e("fragment=", fr.getClass().getSimpleName());
}
}
});
edited Aug 22 '14 at 13:52
answered Apr 5 '14 at 13:13
ashakirov
5,84332423
5,84332423
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
add a comment |
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
2
2
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
This answer works well in my project since I add every fragment except the root fragment to the back stack. But I guess this answer will not work if the latest added fragment wasn't added to the backstack.
– Arne Evertsson
Aug 15 '14 at 8:15
add a comment |
up vote
34
down vote
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
protected int getFragmentCount() {
return getSupportFragmentManager().getBackStackEntryCount();
}
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
Finally, you can find any of your fragments in your backstack with this method:
private Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
protected Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount() - 1);
}
Hope this helps!
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
add a comment |
up vote
34
down vote
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
protected int getFragmentCount() {
return getSupportFragmentManager().getBackStackEntryCount();
}
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
Finally, you can find any of your fragments in your backstack with this method:
private Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
protected Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount() - 1);
}
Hope this helps!
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
add a comment |
up vote
34
down vote
up vote
34
down vote
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
protected int getFragmentCount() {
return getSupportFragmentManager().getBackStackEntryCount();
}
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
Finally, you can find any of your fragments in your backstack with this method:
private Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
protected Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount() - 1);
}
Hope this helps!
I personnaly tried many of those solutions and ended up with this working solution:
Add this utility method that will be used several times below to get the number of fragments in your backstack:
protected int getFragmentCount() {
return getSupportFragmentManager().getBackStackEntryCount();
}
Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):
getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
Finally, you can find any of your fragments in your backstack with this method:
private Fragment getFragmentAt(int index) {
return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
}
Therefore, fetching the top fragment in your backstack can be easily achieved by calling:
protected Fragment getCurrentFragment() {
return getFragmentAt(getFragmentCount() - 1);
}
Hope this helps!
edited Mar 26 '16 at 12:10
answered Jan 20 '15 at 13:20
ptitvinou
7811718
7811718
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
add a comment |
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
This is most accurate solution that I've tried
– mes
Mar 25 '16 at 13:13
add a comment |
up vote
5
down vote
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
public Fragment getTopFragment() {
List<Fragment> fragentList = fragmentManager.getFragments();
Fragment top = null;
for (int i = fragentList.size() -1; i>=0 ; i--) {
top = (Fragment) fragentList.get(i);
if (top != null) {
return top;
}
}
return top;
}
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
add a comment |
up vote
5
down vote
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
public Fragment getTopFragment() {
List<Fragment> fragentList = fragmentManager.getFragments();
Fragment top = null;
for (int i = fragentList.size() -1; i>=0 ; i--) {
top = (Fragment) fragentList.get(i);
if (top != null) {
return top;
}
}
return top;
}
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
add a comment |
up vote
5
down vote
up vote
5
down vote
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
public Fragment getTopFragment() {
List<Fragment> fragentList = fragmentManager.getFragments();
Fragment top = null;
for (int i = fragentList.size() -1; i>=0 ; i--) {
top = (Fragment) fragentList.get(i);
if (top != null) {
return top;
}
}
return top;
}
There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:
public Fragment getTopFragment() {
List<Fragment> fragentList = fragmentManager.getFragments();
Fragment top = null;
for (int i = fragentList.size() -1; i>=0 ; i--) {
top = (Fragment) fragentList.get(i);
if (top != null) {
return top;
}
}
return top;
}
edited Feb 6 '16 at 8:03
answered Jan 17 '16 at 19:10
Erez
6714
6714
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
add a comment |
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
This should be the selected answer!!! Thanks so much :)
– Ben Marten
Feb 4 '16 at 23:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Not reliable. Three reasons: 1) This is a list of all fragments the fragment manager knows about, not just those on the stack. 2) There is no guarantee that the fragment manager will keep adding new ones at the end of the list. Sure, it will do so in simple tests, but what if a fragment is removed, leaving a null, and then under some circumstances the fragment manager decides to reuse that empty slot? Not saying it does, but there is no guarantee it never will, under any circumstances. 3) If you or some future programmer starts using attach/detach to manage fragments, this won't match stack.
– ToolmakerSteve
Sep 20 '16 at 11:45
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
Hi, thanks for your solution but it is not beautiful and easy
– Muhammad Ali
Oct 17 at 8:16
add a comment |
up vote
4
down vote
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
add a comment |
up vote
4
down vote
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
add a comment |
up vote
4
down vote
up vote
4
down vote
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
edited Nov 21 '16 at 9:24
Ziem
3,97274172
3,97274172
answered Oct 30 '12 at 16:40
Eduardo
11617
11617
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
add a comment |
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
This will only work if you give all the fragment the same tag, which is not a good idea if you want to find a specific fragment later.
– Shirane85
Feb 23 '17 at 5:34
add a comment |
up vote
3
down vote
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
int lastFragmentCount = getBackStackEntryCount() - 1;
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
|
show 4 more comments
up vote
3
down vote
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
int lastFragmentCount = getBackStackEntryCount() - 1;
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
|
show 4 more comments
up vote
3
down vote
up vote
3
down vote
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
int lastFragmentCount = getBackStackEntryCount() - 1;
you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()
int lastFragmentCount = getBackStackEntryCount() - 1;
edited Nov 21 '16 at 9:23
Ziem
3,97274172
3,97274172
answered Mar 14 '12 at 12:50
Blackbelt
126k22208236
126k22208236
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
|
show 4 more comments
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
9
9
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
But how can I get the last fragment in backstack?? The popBackStackEntryAt() only returns an BackStackEntry instance, NOT fragment
– Leem.fin
Mar 14 '12 at 12:53
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
yes you are right, but every BackStackEntry holds and id which you can retrive with getId(). you can use this Id in order to retrieve the fragment
– Blackbelt
Mar 14 '12 at 12:55
1
1
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
To get the last fragment : getBackStackEntryCount() - 1
– An-droid
Apr 8 '13 at 9:12
3
3
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
This answer is wrong, I'm seeing the backstack entries have an id of 0, so can't retrieve the fragment by id.
– Justin
May 29 '14 at 15:53
1
1
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
This is old, but for anybody that wanders here: back stack does not hold fragments, but fragment transactions, that's why this answer is wrong
– maciekjanusz
May 31 '16 at 16:31
|
show 4 more comments
up vote
3
down vote
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
add a comment |
up vote
3
down vote
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
add a comment |
up vote
3
down vote
up vote
3
down vote
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
edited Jun 15 at 21:07
Jorgesys
90.9k15234206
90.9k15234206
answered Oct 17 '17 at 7:17
roghayeh hosseini
10618
10618
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
add a comment |
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
Thanks. The most elegant answer. Added it here for Kotlin lovers stackoverflow.com/a/47336504/1761406
– Shirane85
Nov 16 '17 at 18:14
add a comment |
up vote
2
down vote
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
add a comment |
up vote
2
down vote
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
add a comment |
up vote
2
down vote
up vote
2
down vote
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
answered Aug 15 '14 at 8:31
Arne Evertsson
13.8k155978
13.8k155978
add a comment |
add a comment |
up vote
1
down vote
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager
and its backstack. Here's how you can do it:
public class FragmentStackManager {
private final FragmentManager fragmentManager;
private final int containerId;
private final List<Fragment> fragments = new ArrayList<>();
public FragmentStackManager(final FragmentManager fragmentManager,
final int containerId) {
this.fragmentManager = fragmentManager;
this.containerId = containerId;
}
public Parcelable saveState() {
final Bundle state = new Bundle(fragments.size());
for (int i = 0, count = fragments.size(); i < count; ++i) {
fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
}
return state;
}
public void restoreState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
int index = 0;
while (true) {
final Fragment fragment =
fragmentManager.getFragment(bundle, Integer.toString(index));
if (fragment == null) {
break;
}
fragments.add(fragment);
index += 1;
}
}
}
public void replace(final Fragment fragment) {
fragmentManager.popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.clear();
fragments.add(fragment);
}
public void push(final Fragment fragment) {
fragmentManager
.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.add(fragment);
}
public boolean pop() {
if (isEmpty()) {
return false;
}
fragmentManager.popBackStackImmediate();
fragments.remove(fragments.size() - 1);
return true;
}
public boolean isEmpty() {
return fragments.isEmpty();
}
public int size() {
return fragments.size();
}
public Fragment getFragment(final int index) {
return fragments.get(index);
}
}
Now instead of adding and removing fragments by calling FragmentManager
directly, you should use push()
, replace()
, and pop()
methods of FragmentStackManager
. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1)
.
But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
final List<Fragment> fragments = fragmentManager.getFragments();
final List<Fragment> topFragments = new ArrayList<>();
for (final Fragment fragment : fragments) {
if (fragment != null && fragment.isResumed()) {
topFragments.add(fragment);
}
}
return topFragments;
}
}
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack
has been called:
package android.support.v4.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
if (fragmentManager.getBackStackEntryCount() == 0) {
return Collections.emptyList();
}
final List<Fragment> fragments = new ArrayList<>();
final int count = fragmentManager.getBackStackEntryCount();
final BackStackRecord record =
(BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
BackStackRecord.Op op = record.mHead;
while (op != null) {
switch (op.cmd) {
case BackStackRecord.OP_ADD:
case BackStackRecord.OP_REPLACE:
case BackStackRecord.OP_SHOW:
case BackStackRecord.OP_ATTACH:
fragments.add(op.fragment);
}
op = op.next;
}
return fragments;
}
}
Please notice that in this case you have to put this class into android.support.v4.app
package.
add a comment |
up vote
1
down vote
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager
and its backstack. Here's how you can do it:
public class FragmentStackManager {
private final FragmentManager fragmentManager;
private final int containerId;
private final List<Fragment> fragments = new ArrayList<>();
public FragmentStackManager(final FragmentManager fragmentManager,
final int containerId) {
this.fragmentManager = fragmentManager;
this.containerId = containerId;
}
public Parcelable saveState() {
final Bundle state = new Bundle(fragments.size());
for (int i = 0, count = fragments.size(); i < count; ++i) {
fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
}
return state;
}
public void restoreState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
int index = 0;
while (true) {
final Fragment fragment =
fragmentManager.getFragment(bundle, Integer.toString(index));
if (fragment == null) {
break;
}
fragments.add(fragment);
index += 1;
}
}
}
public void replace(final Fragment fragment) {
fragmentManager.popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.clear();
fragments.add(fragment);
}
public void push(final Fragment fragment) {
fragmentManager
.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.add(fragment);
}
public boolean pop() {
if (isEmpty()) {
return false;
}
fragmentManager.popBackStackImmediate();
fragments.remove(fragments.size() - 1);
return true;
}
public boolean isEmpty() {
return fragments.isEmpty();
}
public int size() {
return fragments.size();
}
public Fragment getFragment(final int index) {
return fragments.get(index);
}
}
Now instead of adding and removing fragments by calling FragmentManager
directly, you should use push()
, replace()
, and pop()
methods of FragmentStackManager
. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1)
.
But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
final List<Fragment> fragments = fragmentManager.getFragments();
final List<Fragment> topFragments = new ArrayList<>();
for (final Fragment fragment : fragments) {
if (fragment != null && fragment.isResumed()) {
topFragments.add(fragment);
}
}
return topFragments;
}
}
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack
has been called:
package android.support.v4.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
if (fragmentManager.getBackStackEntryCount() == 0) {
return Collections.emptyList();
}
final List<Fragment> fragments = new ArrayList<>();
final int count = fragmentManager.getBackStackEntryCount();
final BackStackRecord record =
(BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
BackStackRecord.Op op = record.mHead;
while (op != null) {
switch (op.cmd) {
case BackStackRecord.OP_ADD:
case BackStackRecord.OP_REPLACE:
case BackStackRecord.OP_SHOW:
case BackStackRecord.OP_ATTACH:
fragments.add(op.fragment);
}
op = op.next;
}
return fragments;
}
}
Please notice that in this case you have to put this class into android.support.v4.app
package.
add a comment |
up vote
1
down vote
up vote
1
down vote
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager
and its backstack. Here's how you can do it:
public class FragmentStackManager {
private final FragmentManager fragmentManager;
private final int containerId;
private final List<Fragment> fragments = new ArrayList<>();
public FragmentStackManager(final FragmentManager fragmentManager,
final int containerId) {
this.fragmentManager = fragmentManager;
this.containerId = containerId;
}
public Parcelable saveState() {
final Bundle state = new Bundle(fragments.size());
for (int i = 0, count = fragments.size(); i < count; ++i) {
fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
}
return state;
}
public void restoreState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
int index = 0;
while (true) {
final Fragment fragment =
fragmentManager.getFragment(bundle, Integer.toString(index));
if (fragment == null) {
break;
}
fragments.add(fragment);
index += 1;
}
}
}
public void replace(final Fragment fragment) {
fragmentManager.popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.clear();
fragments.add(fragment);
}
public void push(final Fragment fragment) {
fragmentManager
.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.add(fragment);
}
public boolean pop() {
if (isEmpty()) {
return false;
}
fragmentManager.popBackStackImmediate();
fragments.remove(fragments.size() - 1);
return true;
}
public boolean isEmpty() {
return fragments.isEmpty();
}
public int size() {
return fragments.size();
}
public Fragment getFragment(final int index) {
return fragments.get(index);
}
}
Now instead of adding and removing fragments by calling FragmentManager
directly, you should use push()
, replace()
, and pop()
methods of FragmentStackManager
. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1)
.
But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
final List<Fragment> fragments = fragmentManager.getFragments();
final List<Fragment> topFragments = new ArrayList<>();
for (final Fragment fragment : fragments) {
if (fragment != null && fragment.isResumed()) {
topFragments.add(fragment);
}
}
return topFragments;
}
}
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack
has been called:
package android.support.v4.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
if (fragmentManager.getBackStackEntryCount() == 0) {
return Collections.emptyList();
}
final List<Fragment> fragments = new ArrayList<>();
final int count = fragmentManager.getBackStackEntryCount();
final BackStackRecord record =
(BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
BackStackRecord.Op op = record.mHead;
while (op != null) {
switch (op.cmd) {
case BackStackRecord.OP_ADD:
case BackStackRecord.OP_REPLACE:
case BackStackRecord.OP_SHOW:
case BackStackRecord.OP_ATTACH:
fragments.add(op.fragment);
}
op = op.next;
}
return fragments;
}
}
Please notice that in this case you have to put this class into android.support.v4.app
package.
Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.
If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager
and its backstack. Here's how you can do it:
public class FragmentStackManager {
private final FragmentManager fragmentManager;
private final int containerId;
private final List<Fragment> fragments = new ArrayList<>();
public FragmentStackManager(final FragmentManager fragmentManager,
final int containerId) {
this.fragmentManager = fragmentManager;
this.containerId = containerId;
}
public Parcelable saveState() {
final Bundle state = new Bundle(fragments.size());
for (int i = 0, count = fragments.size(); i < count; ++i) {
fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
}
return state;
}
public void restoreState(final Parcelable state) {
if (state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
int index = 0;
while (true) {
final Fragment fragment =
fragmentManager.getFragment(bundle, Integer.toString(index));
if (fragment == null) {
break;
}
fragments.add(fragment);
index += 1;
}
}
}
public void replace(final Fragment fragment) {
fragmentManager.popBackStackImmediate(
null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.clear();
fragments.add(fragment);
}
public void push(final Fragment fragment) {
fragmentManager
.beginTransaction()
.replace(containerId, fragment)
.addToBackStack(null)
.commit();
fragmentManager.executePendingTransactions();
fragments.add(fragment);
}
public boolean pop() {
if (isEmpty()) {
return false;
}
fragmentManager.popBackStackImmediate();
fragments.remove(fragments.size() - 1);
return true;
}
public boolean isEmpty() {
return fragments.isEmpty();
}
public int size() {
return fragments.size();
}
public Fragment getFragment(final int index) {
return fragments.get(index);
}
}
Now instead of adding and removing fragments by calling FragmentManager
directly, you should use push()
, replace()
, and pop()
methods of FragmentStackManager
. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1)
.
But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.
The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
final List<Fragment> fragments = fragmentManager.getFragments();
final List<Fragment> topFragments = new ArrayList<>();
for (final Fragment fragment : fragments) {
if (fragment != null && fragment.isResumed()) {
topFragments.add(fragment);
}
}
return topFragments;
}
}
The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack
has been called:
package android.support.v4.app;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BackStackHelper {
public static List<Fragment> getTopFragments(
final FragmentManager fragmentManager) {
if (fragmentManager.getBackStackEntryCount() == 0) {
return Collections.emptyList();
}
final List<Fragment> fragments = new ArrayList<>();
final int count = fragmentManager.getBackStackEntryCount();
final BackStackRecord record =
(BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
BackStackRecord.Op op = record.mHead;
while (op != null) {
switch (op.cmd) {
case BackStackRecord.OP_ADD:
case BackStackRecord.OP_REPLACE:
case BackStackRecord.OP_SHOW:
case BackStackRecord.OP_ATTACH:
fragments.add(op.fragment);
}
op = op.next;
}
return fragments;
}
}
Please notice that in this case you have to put this class into android.support.v4.app
package.
answered Feb 11 '16 at 22:19
Michael
39.7k16104126
39.7k16104126
add a comment |
add a comment |
up vote
1
down vote
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
fun getTopFragment(): Fragment? {
supportFragmentManager.run {
return when (backStackEntryCount) {
0 -> null
else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
}
}
}
*This should be called from inside an Activity.
Enjoy :)
add a comment |
up vote
1
down vote
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
fun getTopFragment(): Fragment? {
supportFragmentManager.run {
return when (backStackEntryCount) {
0 -> null
else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
}
}
}
*This should be called from inside an Activity.
Enjoy :)
add a comment |
up vote
1
down vote
up vote
1
down vote
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
fun getTopFragment(): Fragment? {
supportFragmentManager.run {
return when (backStackEntryCount) {
0 -> null
else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
}
}
}
*This should be called from inside an Activity.
Enjoy :)
Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)
fun getTopFragment(): Fragment? {
supportFragmentManager.run {
return when (backStackEntryCount) {
0 -> null
else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
}
}
}
*This should be called from inside an Activity.
Enjoy :)
answered Nov 16 '17 at 18:12
Shirane85
1,3891832
1,3891832
add a comment |
add a comment |
up vote
0
down vote
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
add a comment |
up vote
0
down vote
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
add a comment |
up vote
0
down vote
up vote
0
down vote
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...
answered Nov 3 '14 at 14:33
Евгений Шевченко
47037
47037
add a comment |
add a comment |
up vote
0
down vote
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
add a comment |
up vote
0
down vote
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
add a comment |
up vote
0
down vote
up vote
0
down vote
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.
I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.
answered Sep 13 '17 at 17:00
htafoya
9,56794460
9,56794460
add a comment |
add a comment |
up vote
0
down vote
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
add a comment |
up vote
0
down vote
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
add a comment |
up vote
0
down vote
up vote
0
down vote
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
edited Nov 10 at 16:26
answered Nov 10 at 16:17
Vasily Kravchenko
214
214
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9702216%2fget-the-latest-fragment-in-backstack%23new-answer', 'question_page');
}
);
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password