How to replace top fragment? - android

I have an application with 4 fragments: MainFragment, ActionFragment, DoneFragment, FailedFragment. When application launched it shows MainFragment. Than application receive some event and show ActionFragment with two buttons 'yes' and 'no'. If user press 'yes', applicaiton shows DoneFragment, otherwise FailedFragment. When user press one time to back button on ActionFragment, DoneFragment or FailedFragment application must show MainFragment.
Improtant: if ActionFragment, DoneFragment or FailedFragment already opened and some event is occure again, application should show ActionFragment fragment with new event data.
So, I need:
if ActionFragment, DoneFragment or FailedFragment already opened and event occur, I should replace top fragment with ActionFragment
Otherwise I should simply add ActionFragment.
I am trying:
fun addOrReplaceFragment(fragment: Fragment, tag: String) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
val previous = fragmentManager.findFragmentByTag(tag)
if (previous == null) {
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
fragmentTransaction.add(R.id.main_fragment_container, fragment, tag)
fragmentTransaction.addToBackStack(tag)
} else {
fragmentManager.popBackStack(previous.id, 0)
fragmentTransaction.remove(previous)
fragmentTransaction.add(R.id.main_fragment_container, fragment, tag)
fragmentTransaction.addToBackStack(tag)
}
fragmentTransaction.commitAllowingStateLoss()
}
// ...
addOrReplaceFragment(ActionFragment(), "singleTag")
// ...
addOrReplaceFragment(DoneFragment(), "singleTag")
// ...
addOrReplaceFragment(FailedFragment(), "singleTag")
Here is popBackStack() doesn't work. When ActionFragment is opened, DoneFragment or FailedFragment just adding above. And user have to press back two times to get back to MainFragment.
I am find solution change popBackStack() to popBackStackImmediate(). It works well, but if activity is minimized it produce crash with IllegalStateException, because popBackStackImmediate() cannot be called after onSaveInstanceState().
How to replace top fragment and avoid IllegalStateException?

Try this :
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.FragmentToBeReplaced,theFragmentToBeAdded);
ft.commit();

https://developer.android.com/reference/android/app/FragmentManager.html#isStateSaved()
Use isStateSaved to avoid losing state when a transaction happened.
And I think Android navigation component might be easier way to navigate between fragments.

Related

Back From fragment B to Fragment A not working Kotlin

I have two fragments in my Kotlin code.
When I'm pressing some of the buttons then the First fragment will inflate the second fragment.
The second fragment is displayed and all works fine but when I'm pressing the back button then the Phone is going to the Home page (The application is minimized), when I click on the Recently viewed apps that open all the Opened applications on the screen and choosing my Application (that is opened) then the application got back to Fragment Alike its suppose to be.
But I don't understand why the application is minimized when I'm clicking on the back button?
I just want it to go back to fragment A and do not minimize the application.
This is the code to inflate the second fragment:
val fragment2 = details_frag()
val fragmentManager: FragmentManager? = fragmentManager
val fragmentTransaction: FragmentTransaction =
fragmentManager!!.beginTransaction()
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
fragmentTransaction.apply {
replace(R.id.fragSec, fragment2)
commit()
}
} else {
fragmentTransaction.apply {
replace(R.id.flFragment, fragment2)
commit()
}
}
The Code in the Main Activity that inflate the first fragment is:
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
supportFragmentManager.beginTransaction().apply {
replace(R.id.fragLand, firstFrag)
commit()
}
supportFragmentManager.beginTransaction()
.add(
R.id.fragSec,
details_frag::class.java,
null
) // .addToBackStack(null)
.commit()
} else {
supportFragmentManager.beginTransaction().apply {
replace(R.id.flFragment, firstFrag)
commit()
}
}
I don't see something unusual here, it all works just great but it's just minimize my app when I'm going from the second fragment to the first fragment...
(The first is inserted inside the Main Activity like you can see and I just swap the first fragment with the second one when someone clicks on something in my code...)
Thank you!!!
You need to call addToBackstack in the FragmentTransaction (like you're doing in the second example). That makes the current transaction you're performing (replacing fragment A with B) a new state on the stack. Then when the user hits back, that state can be popped off and the transaction reversed, so you're back with fragment A in place.
If you don't add the transaction to the backstack, it becomes part of the most recent state, which is when you added A - that state becomes "added A and then replaced it with B", and when you pop that off, it goes back to "before you added A"

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)

Android fragment simple backstack

I have one activity containing one container that will receive 2 fragments.
Once the activity initialises i start the first fragment with:
showFragment(new FragmentA());
private void showFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment, fragment.getTag())
.addToBackStack(fragment.getTag())
.commit();
}
Then when the user clicks on FragmentA, I receive this click on Activity level and I call:
showFragment(new FragmentB());
Now when I press back button it returns to fragment A (thats correct) and when i press again back button it show empty screen (but stays in the same activity). I would like it to just close the app (since the activity has no parent).
There are a lot of posts related with Fragments and backstack, but i can't find a simple solution for this. I would like to avoid the case where I have to check if im doing back press on Fragment A or Fragment B, since i might extend the number of Fragments and I will need to maintain that method.
You are getting blank screen because when you add first fragment you are calling addToBackStack() due to which you are adding a blank screen unknowingly!
now what you can do is call the following method in onBackPressed() and your problem will be solved
public void moveBack()
{
//FM=fragment manager
if (FM != null && FM.getBackStackEntryCount() > 1)
{
FM.popBackStack();
}else {
finish();
}
}
DO NOT CALL SUPER IN ONBACKPRESSED();
just call the above method!
addToBackStack(fragment.getTag())
use it for fragment B only, not for fragment A
I think your fragment A is not popped out correctly, try to use add fragment rather replace to have proper back navigation, however You can check count of back stack using:
FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
and you can also directly call finish() in activity onBackPressed() when you want your activity to close on certain fragment count.

Android reload fragments stack on restore

I’m developing an android application that makes heavy use of fragments, I’m running into an issue and I’ve been unable to find a solution so far.
The flow is this: the app is launched and MainActivity is the first responder, now, depending on user interaction several fragments gets loaded and pushed onto the stack.
Here is an example:
Main Activity -> fragment A -> fragment B -> fragment C -> etc..
Back history is enabled like so:
fragment C -> fragment B -> fragment A -> etc..
Everything works perfectly fine as long as my application is in foreground but everything breaks when the application goes in background.
If I’m on fragment B for example and I press the home button the application goes in background and when I restore it back it starts from MainActivity with fragment A.
Also, the toolbar shows the title of fragment B and, since fragment A contains a recyclerview I can see parts of fragment B between item rows, like a background image.
This is how I load fragments:
public void loadFragment(Fragment fragment, Boolean addToStack) {
// Load fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.addToBackStack(null);
// show back button
if (addToStack) {
// Code to show the back button.
}
else if (fragmentManager.getBackStackEntryCount() > 0 && !addToStack) {
hideBackButton();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
fragmentTransaction.commitAllowingStateLoss();
}
I call this function from MainActivity and from the fragments:
MyFragment theFragment = new MyFragment();
MainActivity.instance.loadFragment(theFragment, true);
What I want to achieve is that when the application is restored it gets straight to the previously loaded fragment, keeping the entire "back" history. How can I do this?
I'm not sure if other portions of code are needed, but if so I'll post them as required.
call the onResume() function:
public void onResume(){
Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("Your_Fragment_TAG");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
Ok so, after a lot of research I found the issue… and the issue was a mistake of mine.
I’d like to report it here for everyone that might run into the same issue.
At first I tried to force fragment replacement on onResume() function like so:
Fragment f = getSupportFragmentManager().findFragmentById(R.id.container);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, f);
fragmentTransaction.addToBackStack(null);
However android should handle all of this automatically, at least in my knowledge, and so I tried to dig further and I finally narrowed it down to my onStart() method.
Basically I was registering the EventBus and making a function call
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
UserNetworkManager userNetworkManager = new UserNetworkManager(MainActivity.mainActivity);
userNetworkManager.fetchFeed();
}
This code was creating the issue and after all it was not necessary to put it there, so I moved it to the onCreate() method, cleaned up my code a little bit and everything works fine now.

Switching between fragments with back button

Ok i have an activity with one main fragment, that has a menu on it. When a user clicks on a menu item another fragment is animated into the screen, with this code:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
ft.hide(getFragmentManager().findFragmentByTag("menu_fragment"));
Fragment opisFragment = getFragmentManager().findFragmentByTag("opis_fragment");
if (opisFragment == null) {
opisFragment = new OpisFragment();
ft.add(R.id.p_container, opisFragment, "opis_fragment");
ft.commit();
} else {
ft.show(opisFragment);
}
Note: pr_fragment is the tag of the current fragment, the one that has the menu.
Now, this works well, but when i'm on the second fragment i want to add the functionality, that when the user clicks the back button it will show the first fragment. With this code, when i click back it exits the activity alltogether.
Thank you for the help!
All you need is to use addToBackStack(String name) of FragmentTransaction
// Showing menu fragment also added in backstack
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
.add(R.id.p_container, menuFragment, "menu_fragment")
.addToBackStack("menu_fragment")
.commit();
// Showing opis fragment also added in backstack
FragmentTransaction ft2 = getFragmentManager().beginTransaction();
ft2.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
.add(R.id.p_container, opisFragment, "opis_fragment")
.addToBackStack("opis_fragment")
.commit();
Assuming "opis fragment" is in foreground, when you press back button, "menu_fragment" will be displayed back to the foreground, pressing back button again will exit the activity.
With this code, when i click back it exits the activity alltogether.
Normal because there is just your activity in your app stack. the addToBackStack() method is what you are looking for.
if (opisFragment == null) {
opisFragment = new OpisFragment();
ft.add(R.id.p_container, opisFragment, "opis_fragment");
ft.addToBackStack("tag"); // <<< this line
ft.commit();
}
From the doc :
Before you call commit(), however, you might want to call addToBackStack(), in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows the user to return to the previous fragment state, by pressing the Back button.
in mainactivity you can check fragments count if fragments count more than one we will show back button
if(getSupportFragmentManager().getBackStackEntryCount() > 0)
{
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
else
{
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}

Categories

Resources