How to go back to root fragment from 3rd/ 4th/5th fragment? - android

I have fragments in stack like Main frag --> A frag --> B frag --> C frag --> D frag.
How can I go back to main fragment from any of A, B, C, D fragment. For eg: if i clicked button in D, I should be back to Main fragment. Same should happen in case of button click on fragment C. And, on back button click from Main fragment, it should not go back to Fragment D or C.
I tried to pop out all fragment from stack & start again from main fragment. But it doesn't work.
private void onButtonClick(){
MainFragment mainFrag= new MainFragment();
getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//pop back stack inclusive pops all fragment
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.mainFragment, mainFragment).addToBackStack(null).commit();
}
Edit : Ok, it looks like above code is going back to main fragment. But after showing Main fragment for a second, the app minimizes. After main fragment minimizes, following log is shown on Android logcat.
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 570
V/FA: Activity paused, time: 14995077
V/FA: Inactivity, disconnecting from the service

If MainActivity is your frameLayout place , here is my answer:
//just add a switch method on your activity
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack(null);
transaction.commit();
}
and use it in any fragments for your button like this:
private void onButtonClick(){
(MainActivity)getActivity()).switchFragment(new the fragment));
}
Hope it can help~

getSupportFragmentManager().popBackStackImmediate(mainFragment.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);

Related

Conditional Navigation in Android Navigation Component

I have 3 fragments A, B and C with A being the start destination of my nav graph. When the user starts the app, I check in fragment A if there are previously stored results. If there are, I want to navigate straight to fragment C. I have managed to get this to work. However, when the user presses back in fragment C in this case, I want them to be taken to fragment B instead of A, and that's what I need help figuring out.
Note: Fragment A is just a setup fragment which is only visited once when the app starts. Which means when the user presses back from fragment B, they are taken to OS home screen.
You can override onBackPress() and replace whatever fragment you are in with FragmentB like this
#Override
public void onBackPressed() {
int stackCount = getFragmentManager().getBackStackEntryCount();
if (stackCount == 1) {
super.onBackPressed(); // if you don't have any fragments in your backstack yet.
} else {
// just replace container with fragment as you normally do;
FragmentManager fm = getFragmentManager();
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//clear backstackfirst and then you can exit the app onbackpressed from home fr
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.container, new FragmentB());
transaction.commit();
}
}
This is the original answer ,you can take a look answer by Rainmaker
You can override your onBackPressed on fragment C and call your navController to go back to fragment b creating a new action from C to B
navController.navigate(R.id.action_CFragment_to_BFragment)

Return from activity to last visited intent

I have a main activity that exists out of three fragments. Fragment 2 is the main fragment. On fragment 3 I have a button. Once I click the button it directs the user to a ChatActivity. The ChatActivity has an onBackButtonPressed that should return the user back to fragment 3. However, it seems that it would always return the user to fragment 2 (the main fragment).
How can I bring the user to the fragment they last visited, or at least back to fragment 3?
Edit:
I added this block of code in the button onClick function:
ChatFragment fragment = new ChatFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.main_tabPager, fragment);
transaction.addToBackStack(null);
transaction.commit();
When I click the back button in the activity it does not return me to fragment 3 but instead rebuild the fragmentpager and start back at Fragment 2.
When you are opening fragment 3 from main fragment (fragment 2), add fragment 3 into backstack like this:
Fragment3 fragment3 = new Fragment3();
getSupportFragmentManager().beginTransaction().add(R.id.content, fragment3).addToBackStack(null).commit();
You should add all fragments to backstack that you want to return to
Ideally addToBackStack() on fragment transaction should be enough as per documentation, but it seems not true at times, so we have to handle the popping up of the back stack upon Back button pressed by ourselves. I added this to my activity and it worked as expected:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Hope it helps.

How to remove Fragment transactions in middle

I have 5 fragments(say A, B, C, D, E) and one activity with a container.
Whenever i want to add a fragment to a container I'll be using the following code.
getSupportFragmentManager().beginTransaction().replace(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();
Let's say i added Fragment A.
Upon some action in A, I added fragment B.
Upon some action in B, I added fragment C.
Upon some action in C, I added fragment D.
Upon some action in D, I added fragment E.
Now my stack should be as follows.
A -> B -> C -> D -> E
Now upon some action in Fragment E, I need to remove fragments D, C, B so that when user click back, he should directly see Fragment A.
I tried using following code.
public void removeScreen(#NonNull String tag) {
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentByTag(tag);
if (fragment != null) {
FragmentTransaction trans = manager.beginTransaction();
trans.remove(fragment);
trans.commitAllowingStateLoss();
}
}
Upon some action in Fragment E, I called the above function with Tags of Fragment D, C, B(Tags are same as the one that i used for fragment transaction).
Now when i click back button fragment D is becoming visible but i was expecting fragment A.
It would be very helpful if somebody points out where am i going wrong.
If you want to reach exactly the same behavior that you've described, you can do it by this way:
FragmentManager manager = getSupportFragmentManager();
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
This will clear all backstack until the bottom of stack will be reached.
I prefer using DialogFragment for this reason and pop them using interface callbacks and dismiss() function inside them. This is the easiest and quick way to implement what you are trying to do.
I think your problem occur here :
replace :
getSupportFragmentManager().beginTransaction().replace(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();
to:
getSupportFragmentManager().beginTransaction().add(R.id.mainContainerRL, fragment, tag).addToBackStack(tag).commit();
when you add your fragment to container,tou just add it ,if use"replace" method,you romove it from activirty's fagment manager,it case your "removeScreen" method did not work

Going from 3rd to 1st fragment in the backstack: Android

I have a sequence of event via which i have added three fragments to the backstack, one by one. Each of these fragments covers the full screen of the activity.
I have stored the is returned from the commit of Frag1.
Now in Frag3, based on a specific click, I want to go back to Frag1 directly and discard/pop all Fragments in between.
So, when this button is clicked i send a message to the activity which does the following:
getSupportFragmentManager().popBackStack(mFrag1Id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
But i just got a blank screen, so i assume no fragment was loaded.
I even tried:
In commit - fragmentTransaction.addToBackStack("Fragment1");
and then
getSupportFragmentManager().popBackStack("Fragment1", FragmentManager.POP_BACK_STACK_INCLUSIVE);
But it doesn't work.
Could someone please help me with this?
Thanks.
OK so I found the issue.
FragmentManager.POP_BACK_STACK_INCLUSIVE pops all the fragments including the one whose id passed as argument.
SO for example:
getSupportFragmentManager().popBackStack(mFrag1Id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
Here it will pop everything on the stack including fragment whose id id mFrag1Id.
from third fragment you should call popBackStack();
twice (one to remove third fragment and the second to remove second fragment )
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.remove(ThirdFragment.this);
transaction.commit();
fm.popBackStack();
fm.popBackStack();
When you opened Fragment A and you Navigated to Fragment B and then to Fragment C and then You want to close Fragment C and B and land on Fragment A
Now in some scenario, you want to close Fragment C and Fragment B and you want to land on Fragment A... then use this logic of FragmentManager to do such task.
First get the number of fragment entries in back stack (When we are adding any fragment to addToBackStack("Frag1")) at that time fragment back stack entry will increase.
so get using this
FragmentManager fmManager = activity.getSupportFragmentManager();
Log.e("Total Back stack Entry: ", fmManager.getBackStackEntryCount() + "");
Now assume, you want to close current fragment (Fragment C) and your last fragment (Fragment B) so simple logic is getBackStackEntryCount -2 and at that time your back stack entry count will be 3 (Fragment A, Fragment B and Fragment C)
Here -2 is for because we want to go 2 fragment step back (Fragment C
and Fragment B)
So simple two line of Code is:
if (fmManager.getBackStackEntryCount() > 0) {
fmManager.popBackStack(fmManager.getBackStackEntryAt(fmManager.getBackStackEntryCount()-2).getId(), FragmentMaanger.POP_BACK_STACK_INCLUSIVE);
}
You can also do it by adding two time "popBackStack()" and will also work, but it not idle way to do this
FragmentManager fmManager = activity.getSupportFragmentManager();
fmManager.popBackStack();
fmManager.popBackStack();
If you want user to back at the beginning fragment, code snippet below will help you.
public static void popBackStackInclusive(AppCompatActivity activity) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
for (int i = 1; i < fragmentManager.getBackStackEntryCount(); i++){
try {
int fragmentId = fragmentManager.getBackStackEntryAt(i).getId();
fragmentManager.popBackStack(fragmentId, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} catch (Exception e) {
Timber.d("Fragment Back Stack Error: %s", e.getLocalizedMessage());
}
}
}
Also if you want to prevent user to close app when no fragments at back stack, take a look at below.
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
if(fragmentManager.getBackStackEntryCount() > 1) {
super.onBackPressed();
} else {
// TODO: Show dialog if user wants to exit app or;
//finish();
}
}

Android fragments navigation and backstack

I have a header bar (kinda like menu) and 4 fragments (MAIN, A, B, C) from which the MAIN should be 'main/root' fragment for backstack.
Problem i have is when user via menu goes for example MAIN > A > B > C.
If i simply use backstack it will go in reverse order which i don't want.
I need back button to go back to MAIN no matter how user navigated to one of those 3.
My current code (which is wrong, it quits app when not in MAIN and current fragment is switched from other non-MAIN fragment) looks like this:
private void SwitchFragment(Fragment pFragment)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fl_fragmentcontainer, pFragment);
if (_CurrentFragment == _Frag_Main)
ft.addToBackStack(null);
ft.commit();
_CurrentFragment = pFragment;
}
Your stack must contains 2 fragments at maximum
Main is visible
Main is onBackstack / AorBorC is visible.
User click on back ==> Main is visible.
User click on back ==> application end
I suppose A / B / C are displayed in the same view so in this case,
When user click on your Menu, you have to check if A/ B / C is currently displayed and replace it by the one selected by the user.
private void displayFragment(Fragment pFragment) {
Fragment fr = getSupportFragmentManager()
.findFragmentById(R.id.main_fl_fragmentcontainer);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fl_fragmentcontainer, pFragment);
if (_CurrentFragment == _Frag_Main) {
ft.addToBackStack(null);
}
ft.commit();
_CurrentFragment = pFragment;
}
can override OnBackPressed method of your activity.

Categories

Resources