I have an activity which has three fragments. I have also overridden the onBackPressed() method on my activity. When the user navigates to any of my fragments the standard behaviour of the back button occurs. Except for when I launch a fragment not from its "parent".
Imagine this: My activity has no UI. It only has 5 fragments. When the user is on either fragment1, fragment2 or fragment3 and presses the back button he must get out of the app (ie.by calling finish() in only activity the app has). Fragment1Child conceptually is a "child" of fragment1 and fragment2Child is a "child" of fragment2. When going from fragment1 or fragment2 to their children and pressing back I get the expected behaviour. When though, I go from fragment3 to fragment2Child and then press back I am presented correctly with with fragment2. Now when I press back the Activity.finalize() method I have is executed but the app is not closed. Instead I get back to fragment3!
Here is my onBackPressed() method that checks what the is the current fragment shown and decides what to do accordingly
#Override
public void onBackPressed() {
Log.d(TAG, "MainACtivity.onBackPressed()");
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
Log.d("NIBHA", " Drawere ++++++++++++++++++++++");
mDrawerLayout.closeDrawers();
} else {
Fragment fragment = getSupportFragmentManager().findFragmentById(
R.id.fragment_container);
Log.d("Nibha", "" + fragment);
if (fragment instanceof DeliveryOrder
|| fragment instanceof IncomingShipment
|| fragment instanceof RentalAgreement) {
Log.d(TAG, "EXITING APP");
finish();
return;
}
if (fragment instanceof IncomingShipmentDetail
&& getIntent().getAction().equals("RA")) {
Log.d(TAG, "IS DETAIL CALLED FROM RA");
transaction.replace(R.id.fragment_container,
new IncomingShipment());
transaction.commit();
}
super.onBackPressed();
}
}
Problem seems to be that super.onBackPressed(); is not being called. Remove return statement and change the following to else if:
if (fragment instanceof IncomingShipmentDetail
&& getIntent().getAction().equals("RA")) {
Log.d(TAG, "IS DETAIL CALLED FROM RA");
transaction.replace(R.id.fragment_container,
new IncomingShipment());
transaction.commit();
}
Related
Suppose I'm in fragment A, then moving to B, then using Back button returns to A.
In the activity I'm performing the following override:
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
Fragment frag = fm.findFragmentByTag(Consts.A);
if (frag != null){
Log.d(Consts.TAGS.ACTIVITY_ORDER,"");
fm.beginTransaction().remove(frag).commit();
fm.popBackStack();
}
}
and while showing B goes like this:
FragmentManager fm = getActivity().getSupportFragmentManager();
Fragment f = BFragment.newInstance(Consts.B);
fm.beginTransaction()
.replace(R.id.rl_content,
f,
Consts.B)
.addToBackStack(null)
.commit();
Now, which method (if any) will be executed in A, once we execute popBackStack()?
If none, how can we change A's data models or UI components (such as keyboard or a TextView) right after back press? is it component-dependent?
R.id.rl_content is the container.
Please consider 2 cases:
1. A is in R.id.rl and being replaced
2. A is not in R.id.rl and is not being replaced
If you're always going back from Fragment B to Fragment A or vice versa, i would recommend this solution inside the fragments themselves.
#Override
public void onResume() {
super.onResume();
Fragment f = AFragment.newInstance(Consts.A);
if(getView() == null){
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.rl_content, f);
trans.addToBackStack(null);
trans.commit();
return true;
}
return false;
}
});
}
You can freely move from B to A and A to B using the same code. if you would like a more dynamic approach e.g. you would like to go from Fragment A to Fragment C, or Fragment B to Fragment C and then when you press back go back to the previous fragment on stack. I would aim to use Kyle Falconer's Solution here
Incase the link dies, I'll post the code here:
#Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
I haven't tested the second solution, but use the first.
There are quiet a few ways by which you can change A's data models or UI components.
Case 1: when A is in R.id.rl_content and is being replaced by B. In this case you can simply update required models or UI in onCreateView of Fragment A.
Case 2: When A is not being replaced. In this case fragment A doesn't know when to update its view. In the onBackpressed() of your activity you can call Fragment A's updateView() method if Fragment B is being popped.
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
FragmentB fragmentB = (FragmentB)fm.findFragmentByTag(Consts.B);
if (fragmentB != null){
Log.d(Consts.TAGS.ACTIVITY_ORDER,"");
fm.beginTransaction().remove(fragmentB).commit();
fm.popBackStack();
FragmentA fragmentA = (FragmentA)fm.findFragmentByTag(Consts.A);
if (fragmentA != null) {
fragmentA.updateView();
}
}
}
EDIT
I understand that you also want to handle scenarios like hiding keyboard etc.
For this you might want to pass backpress event to the individual fragments. Somewhat like this:
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
FragmentB fragmentB = (FragmentB)fm.findFragmentByTag(Consts.B);
if (fragmentB != null){
if (!fragmentB.onBackPress()) {
// This means fragment B doesn't want to consume backpress therefore remove it.
Log.d(Consts.TAGS.ACTIVITY_ORDER,"");
fm.beginTransaction().remove(fragmentB).commit();
fm.popBackStack();
FragmentA fragmentA = (FragmentA)fm.findFragmentByTag(Consts.A);
if (fragmentA != null) {
fragmentA.updateView();
}
}
}
}
And in your Fragment B create a function onBackPress like this:
public boolean onBackPressed() {
// if keyboard is showing then hide it here and return true to consume the back press event or else return false to dismiss this fragment.
}
I'm having an special use case where I need to switch between two fragments. The issue I'm having is that for the second fragment I need to persist it's state, and the only thing that seems to be working for that is to add it to the BackStack.
I rely on the support fragment manager to replace the fragments:
public void toggle() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment instanceof FragmentB && null != fragmentA) {
// fragment B is visible - we should show fragment A
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.frag_fade_in, R.anim.frag_fade_out,
R.anim.frag_fade_in, R.anim.frag_fade_out)
.replace(R.id.fragment_container, fragmentA)
.commit();
} else if (fragment instanceof FragmentA && null != fragmentB) {
// fragment A is visible - we should show fragment B
boolean isRestored = false;
fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAG_B);
if (null != fragment) {
// Restore fragment state from the BackStack
fragmentB = (FragmentB) fragment;
isRestored = true;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.frag_fade_in,
R.anim.frag_fade_out,
R.anim.frag_fade_in,
R.anim.frag_fade_out);
transaction.replace(R.id.fragment_container, fragmentB, TAG_FRAG_B);
if(!isRestored){
transaction.addToBackStack(TAG_FRAG_B)
}
transaction.commit();
} else {
// Just pop any fragments that were added - usually we won't get in here
getSupportFragmentManager().popBackStack();
}
}
This in combination with the onBackPressed() override:
#Override
public void onBackPressed() {
if (isCurrentFragmentB()) {
toggle();
} else {
// Back key was pressed and we are on fragment A - at this state we simply want to go back to the
// previous section
super.onBackPressed();
}
}
Using this implementation I make sure I reuse fragment B and keep it's state so that it doesn't look like it is created from scratch each time. I also make sure that when I go back, I can go only from fragment B to A and not from fragment A to B.
The issue I encountered is that when super.onBackPressed(); is called and more than one fragment was added(replaced actually, as I want only one active fragment at a time) through the fragment manager, it will throw an exception:
java.lang.IllegalStateException: Fragment already added: FragmentA{af9c26b #0 id=0x7f0e00d3}
This is happening only when the active fragment is FragmentA. I have a suspicion that this is because of the BackStack implementation, but as I've said, I only want the second one to be persisted.
How can I fix this? I am missing something?
I have managed to implement an work-around for this, although it is a little hacky.
Because I need to keep the state of FragmentB, I am forced to add it to the BackStack, but this will actually affect what transition is reversed when onBackPressed() is called.
To avoid this, I had to update the logic for the back press and manually handle that case
#Override
public void onBackPressed() {
if (isCurrentFragmentB()) {
toggle();
} else if (isCurrentFragmentA()) {
getSupportFragmentManager().popBackStackImmediate(TAG_FRAG_A, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// Special case - because we added the fragment B to the BackStack in order to easily resume it's state,
// this will fail as it will actually try to add fragment A again to the fragment manager (it
// will try to reverse the last transaction)
super.finish();
} else {
// Usual flow - let the OS decide what to do
super.onBackPressed();
}
}
Also, I've optimized the toggle method a little bit:
public void toggle() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
#SuppressLint("CommitTransaction") FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.frag_fade_in, R.anim.frag_fade_out,
R.anim.frag_fade_in, R.anim.frag_fade_out);
if (fragment instanceof FragmentB && null != fragmentA) {
// fragment B is visible - we should show fragment A
fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAG_A);
if (null != fragment) {
// Restore fragment state from the BackStack
fragmentA = (FragmentA) fragment;
}
// Replace current fragment with fragment A and commit the transaction
transaction.replace(R.id.fragment_container, fragmentA, TAG_FRAG_A).commit();
} else if (fragment instanceof FragmentA && null != fragmentB) {
// fragment A is visible - we should show fragment B
fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAG_B);
if (null != fragment) {
// Restore fragment state from the BackStack
fragmentB = (FragmentB) fragment;
}
// Replace current fragment with fragment B
transaction.replace(R.id.fragment_container, fragmentB, TAG_FRAG_B);
if (null == fragment) {
// No entry of the fragment B in the BackStack, we want to add it for future uses
transaction.addToBackStack(TAG_FRAG_B);
}
// Commit the transaction
transaction.commit();
} else {
// Just pop any fragments that were added - usually we won't get in here
getSupportFragmentManager().popBackStack();
}
}
I hope this can help others which need an similar flow.
PS: The fragment I want to persist is SupportMapFragment, so that my map isn't always redrawn, re-centered and populated with data every time I want to show it.
I have a main activity that hosts a lot of fragments and a "home page" fragment. Every time I want to add a fragment, I will call this method inside the main activity.
public void addFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.fragmentContainer, fragment, "new_fragment");
ft.addToBackStack("new_fragment").commit();
}
Whenever the user presses the back button of the phone, I want the "home page" fragment to be the last page the user sees before he exits the application. How can I do that? I have tried this inside the onBackPressed() inside the MainActivity but it doesn't work (the back button is not working).
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag("new_fragment");
//if fragment is home page fragment, exit application
//else pop the newest fragment or go to home page fragment
if (fragment == fragDefault) {
finish();
} else {
if(fm.getBackStackEntryCount() == 0){
//display home page fragment here
}
}
}
You can check your back stack when you press the back button/key.
When adding your 'home page' Fragment, don't put it to the back stack.
Add all other Fragments when needed and put them to the back stack.
When user press the back button/key, if the back stack is empty, exit app, else pop up Fragment from back stack.
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
finish();
}
else {
getFragmentManager().popBackStack();
}
Alternatively you might want to try this:
if (f instanceof HomePageFragmentClass) {
finish();
} else {
//f.dosomething();
}
*I have not tested it yet, let me know if it works.
I have an Activity and many fragments inflated in same FrameLayout
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
example: mainActivity > any fragment (press back button) > activity is blank.
In onCreate:
layout = (FrameLayout)findViewById(R.id.content_frame);
layout.setVisibility(View.GONE);
When I start a fragment:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, profileFragment);
ft.addToBackStack(null);
ft.commit();
layout.setVisibility(View.VISIBLE);
I suppose I need to make the frameLayout's visibility GONE again on back pressed, but how do I do this?
I tried onBackPressed and set layout.setVisibility(View.GONE); but I cannot go back through fragments, as I go directly to main page.
If you have more than one fragment been used in the activity or even if you have only one fragment then the first fragment should not have addToBackStack defined. Since this allows back navigation and prior to this fragment the empty activity layout will be displayed.
// fragmentTransaction.addToBackStack() // dont include this for your first fragment.
But for the other fragment you need to have this defined otherwise the back will not navigate to earlier screen (fragment) instead the application might shutdown.
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
} else if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
To add a fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.layout_main, dashboardFragment, getString(R.string.title_dashboard))
.addToBackStack(getString(R.string.title_dashboard))
.commit();
Sorry for the late response.
You don't have to add ft.addToBackStack(null); while adding first fragment.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, profileFragment);
// ft.addToBackStack(null); --remove this line.
ft.commit();
// ... rest of code
If you want to track by the fragments you should override the onBackPressed method, like this
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
}
}
You can override onBackPressed and check to see if there is anything on the backstack.
#Override
public void onBackPressed() {
int fragments = getFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
// make layout invisible since last fragment will be removed
}
super.onBackPressed();
}
Just don't add the first fragment to back stack
Here is the Kotlin code that worked for me.
val ft = supportFragmentManager.beginTransaction().replace(container, frag)
if (!supportFragmentManager.fragments.isEmpty()) ft.addToBackStack(null)
ft.commit()
On a recent personal project, I solved this by not calling addToBackStack if the stack is empty.
// don't add the first fragment to the backstack
// otherwise, pressing back on that fragment will result in a blank screen
if (fragmentManager.getFragments() != null) {
transaction.addToBackStack(tag);
}
Here's my full implementation:
String tag = String.valueOf(mCurrentSectionId);
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
// if the fragment exists then no need to create it, just pop back to it so
// that repeatedly toggling between fragments doesn't create a giant stack
fragmentManager.popBackStackImmediate(tag, 0);
} else {
// at this point, popping back to that fragment didn't happen
// So create a new one and then show it
fragment = createFragmentForSection(mCurrentSectionId);
FragmentTransaction transaction = fragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.main_content, fragment, tag);
// don't add the first fragment to the backstack
// otherwise, pressing back on that fragment will result in a blank screen
if (fragmentManager.getFragments() != null) {
transaction.addToBackStack(tag);
}
transaction.commit();
}
irscomp's solution works if you want to end activity when back button is pressed on first fragment. But if you want to track all fragments, and go back from one to another in back order, you add all fragments to stack with:
ft.addToBackStack(null);
and then, add this to the end of onCreate() to avoid blank screen in last back pressed; you can use getSupportFragmentManager() or getFragmentManager() depending on your API:
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
Final words: I don't suggest you to use this solution, because if you go from fragment1 to fragment 2 and vice versa 10 times, when you press back button 10 times it will do it in back order which users will not want it.
Almost same as Goodlife's answer, but in Xamarin.Android way:
Load fragment (I wrote helper method for that, but it's not necessary):
public void LoadFragment(Activity activity, Fragment fragment, string fragmentTitle = "")
{
var fragmentManager = activity.FragmentManager;
var fragmentTransaction = fragmentManager.BeginTransaction();
fragmentTransaction.Replace(Resource.Id.mainContainer, fragment);
fragmentTransaction.AddToBackStack(fragmentTitle);
fragmentTransaction.Commit();
}
Back button (in MainActivity):
public override void OnBackPressed()
{
if (isNavDrawerOpen()) drawerLayout.CloseDrawers();
else
{
var backStackEntryCount = FragmentManager.BackStackEntryCount;
if (backStackEntryCount == 1) Finish();
else if (backStackEntryCount > 1) FragmentManager.PopBackStack();
else base.OnBackPressed();
}
}
And isNavDrawerOpen method:
bool isNavDrawerOpen()
{
return drawerLayout != null && drawerLayout.IsDrawerOpen(Android.Support.V4.View.GravityCompat.Start);
}
I still could not fix the issue through getBackStackEntryCount() and I solved my issue by making the main page a fragment too, so in the end I have an activity with a FrameLayout only; and all other fragments including the main page I inflate into that layout. This solved my issue.
I had the same problem when dealing with Firebase's Ui Login screen. When back button was pressed it left a blank screen.
To solve the problem I just called finish() in my onStop() method for said Activity. Worked like a charm.
If you have scenario like me where a list fragment opens another details fragment, and on back press you first need to show the list fragment and then get out the whole activity then, addToBackStack for all the fragment transactions.
and then on the activity, do like this (courtesy: #JRomero's answer, #MSaudi's comment)
#Override
public void onBackPressed() {
int fragments = getFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
// make layout invisible since last fragment will be removed
}
super.onBackPressed();
}
Just Comment or Remove transaction.addToBackStack(null) in your code.Below is code to change fragment in kotlin.
fun ChangeFragment(activity: MainActivity, fragment: Fragment) {
val transaction: FragmentTransaction =
activity.getSupportFragmentManager().beginTransaction()
transaction.replace(R.id.tabLayoutContainer, fragment)
transaction.commit()
}
Say I have an activity that has fragments added programmatically:
private void animateToFragment(Fragment newFragment, String tag) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, newFragment, tag);
ft.addToBackStack(null);
ft.commit();
}
What is the best way to return to the previous fragment that was visible?
I found Trigger back-button functionality on button click in Android but I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
Calling finish() just closes the activity which I'm not interested in.
Is there a better way to go about this?
Look at the getFragmentManager().popBackStack() methods (there are several to choose from)
http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
To elaborate on the other answers provided, this is my solution (placed in an Activity):
#Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
When we are updating/add the fragments,
Should Include the .addToBackStack().
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail") // Add this transaction to the back stack (name is an optional name for this back stack state, or null).
.addToBackStack(null)
.commit();
After that if we give the getFragments.popBackStackImmediate() will return true if we add/update the fragments, and move back to the current screen.
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
These answers does not work if i don't have addToBackStack() added to my fragment transaction but, you can use:
getActivity().onBackPressed();
from your any fragment to go back one step;
Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack
`
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStackImmediate();
}
else{
super.onBackPressed();
}
`
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.
On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !
Inside activities on back pressed put this:
Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");
if (home instanceof FragmentDetailedPizza && home.isVisible()) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
//Primary fragment
moveTaskToBack(true);
}
And launch the other fragment like this:
Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();
Kotlin Answer
First, call Fragment Manager.
After, to use onBackPressed()
method.
Coding in Android Studio 4.0 with Kotlin:
fragmentManager?.popBackStack()
Programmatically go back to the previous fragment using following code.
if ( getFragmentManager().getBackStackEntryCount() > 0)
{
getFragmentManager().popBackStack();
return;
}
super.onBackPressed();
To make that fragment come again, just add that fragment to backstack which you want to come on back pressed, Eg:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new LoginFragment();
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack("SignupFragment");
ft.commit();
}
}
});
In the above case, I am opening LoginFragment when Button button is pressed, right now the user is in SignupFragment. So if addToBackStack(TAG) is called, where TAG = "SignupFragment", then when back button is pressed in LoginFragment, we come back to SignUpFragment.
Happy Coding!
By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.
adding new fragment:
view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, new ChangePassword());
transaction.addToBackStack(null);
transaction.commit();
}
});
Following Kotlin code useful to me
1. Added in Simple Activity class with multiple fragments used
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount > 0) {
Log.i(TAG, "=============onBackPressed - Popping backstack====")
supportFragmentManager.popBackStack()
} else {
Log.i(TAG, "=============onBackPressed called because nothing on backstack====")
super.onBackPressed()
}
}
2. Added in BottomNavigationView Activity class with multiple fragments used
override fun onBackPressed() {
Log.e(TAG, "=============onBackPressed")
val navController = findNavController(R.id.nav_host_fragment)
when (navController.currentDestination!!.id) {
R.id.navigation_comments, R.id.navigation_my_posts -> {
menuItemPosition = 0
navController.navigate(R.id.navigation_home)
Log.i(TAG, "=============onBackPressed - Popping backstack with First fragment ====")
}
else -> {
Log.i(TAG, "=============onBackPressed called because nothing on backstack====")
super.onBackPressed()
}
}
}
I came here looking or the same idea, and in the meantime i came up with own, which I believe is not that bad and works if with ViewPager.
So what I did, is to override the onBackPressed method in the parent activity that holds the viewPager, and set it to always go back minus 1 position until it reaches the first fragment, then closes the activity.
#Override
public void onBackPressed() {
if(viewPager.getCurrentItem()>0){
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
} else {
super.onBackPressed();
this.close();
}
}
private void close(){
this.finish();
}
This might have a downfalls, like it only goes back one way left each time, so it might not work great if there are tabs and you switch positions with fragments skipped, ( going from 0 to 2, and then pressing back would put you on 1, instead of 0)
For my case tho, with 2 fragments in viewPager without tabs, it does the job nicely.
getActivity().getSupportFragmentManager().popBackStackImmediate();
OR
getActivity().onBackPressed();
Try below code:
#Override
public void onBackPressed() {
Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (myFragment != null && myFragment instanceof StepOneFragment) {
finish();
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}