I have an activity with 4 fragments associated to it. In one of the fragments I can open another activity. When I am returning from the activity (with calling finish()
) the default fragment is displayed and not the last one. For example: if I have 4 fragments a b c d which associated to activity A, the default displayed fragment is c. From fragment a I can open other activity B. What I want is to see the last fragment seen when returning from activity B back to activity A.

- 8,955
- 18
- 95
- 180
1 Answers
addToBackStack(String) is the method which provides the functionality to have the fragment added to the backStack, so when the back button is pressed th fragments will be displayed in the reverse order of how they were added.
For you scenario in your transactions when you replace or add the fragments (for example) when you do,
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(your layout, fragment a, tag);
ft.addToBackStack(null); // this line will remember fragment a
ft.commit();
After you finish your Activity B. You will be able to see fragment A and if you press back button you will see other fragments in reverse order.
EDIT - To check if a fragment is visible.
Use the isVisile() method of Fragment class to see if this is the current visible fragment.
public final boolean isVisible ()
Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.'
See here as well.

- 1
- 1

- 6,692
- 4
- 39
- 74
-
The above works when back press is performed. If you are only looking for a way to find the visible fragment see my edit. – Atul O Holic Feb 25 '14 at 14:31
-
Is there a way to apply this solution while using the navigation framework? – Haggai Aug 21 '23 at 07:02