I have 3 fragments Fragment1, Fragment2 and Fragment3 and navigation is like
Fragment1->Fragment2->Fragment3
But on back press From Fragment3 go back to Fragment2 after completing some task like from Fragment2. And from Fragment1 finish this activity.
what will be the best method to do this task.
As per your question just you have to add addToBackStack() method before commit() transaction.
for example:
FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.article_fragment, firstFragment)
.addToBackStack(null).commit();
Add second and third fragment same as above manner and just add code in onBackPressed() Override method.
for example:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Please follow the process.
1. When you add fragment add below code to your code
fragmentTransaction.addToBackStack(null);
Then back button handle from the activity.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount()>0){
getFragmentManager().popBackStack();
}else {
super.onBackPressed();
} }
It will be working perfectly. Happy coding.
There is no need to handle OnBackPress inside Fragment. When you performing Fragment transaction, you can put your fragment to BackStack:
When there are FragmentTransaction objects on the back stack and the user presses the Back button, the FragmentManager pops the most recent transaction off the back stack and performs the reverse action (such as removing a fragment if the transaction added it).
More details you can get from this article.
Related
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.
I'm creating LoginActivity-> OtherActivity-> Fragment 1-> Fragment_2. When I click Back Button I'm back in Fragment_1 when again I click BackButton I'm in LoginActivity why?
I want come back to MainActivity after the click BackButton in Fragment _1 and after next click BackButton (in MainActivity) I want come back to home screen
How can I do this ?
In MainActivity i have:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Call addToBackStack when adding fragment. For example:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(backStateName);
ft.commit();
Also, call finish() on your LoginActivity before starting OtherActivity.
At first remove LoginActivity from stack when navigating to OtherActivity. After that use #ahomphophone's answer when presenting fragment. After that back stack should work as expected without needing override 'onBackPressed'.
Note: There is no MainActivity on your provided stack.
Update: If you want to stay in OtherActivity use this code
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ) {
getFragmentManager().popBackStack();
}
}
Popbackstack is working fine when all the fragments in the sequence are added in the backstack but isnt working when one of the transactions is not added in the backstack.
Here is my navigation:
1.Replace fragment to load home fragment. This transaction not added to backstack.
Replace fragment to load login fragment. This transaction is added to backstack.
3.Replace fragment to load loggedin fragment. This transaction is not added to backstack.
Now, when i press back button once nothing happens. Whereas ideally it should go to the home fragment from logged in fragment.
Here is my onbackpressed method in main activity:
#Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()>0)
{
FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1);
String str = backStackEntry.getName();
FragmentManager fm=getSupportFragmentManager();
//getSupportFragmentManager().popBackStackImmediate();
fm.popBackStack(str, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else {
super.onBackPressed();
}
}
popBackstack only 'pop' what is in the backstack.
Since you haven't add the transaction when replacing the LoginFragment by the LoggedInFragment when you press back:
the LoggedInFragment remains,
the LogInFragment is popped
the HomeFragment is displayed
But because the LoggedInFragment as been added after the HomeFragment, the HomeFragment is displayed underneath it. So you can't see it as hidden by the LoggedInFragment.
One solution is to add the transaction to the back stack when you replace the LogInFragment by the LoggedInFragment.
Then in onBackPressed you test if the current fragment is the LoggedInFragment. If it's the case you pop the back stack up to HomeFragment (not inclusive). Like that both LoggedInFragment and LogInFragment will be pop.
EDIT
#Override
public void onBackPressed() {
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment_container);
// If there is something in the back stack AND the current fragment is the LoggedInFragment
if (manager.getBackStackEntryCount() > 0
&& fragment instanceof LoggedInFragment) {
manager.popBackStack(HomeFragment.class.getSimpleName(), 0);
} else {
super.onBackPressed();
}
}
In order to retrieve the HomeFragment by name you need to tag your transaction when you replace the current fragment by the HomeFragment. Generally I tag all transactions with the fragment's class simple name so like that I can retried any fragment:
transaction.replace(R.id.my_fragment_container, fragment, fragment.getClass().getSimpleName());
Eselfar's explanation of the problem is correct, but the code he provided wasn't generic enough for me.
I (hopefully) resolved this issue in a general case by the following code:
#Override
public void onBackPressed() {
Fragment currentFragment = getCurrentFragment();
if (mFragmentManager.getBackStackEntryCount() > 0) {
// In a normal world, just popping back stack would be sufficient, but since android
// is not normal, a call to popBackStack can leave the popped fragment on screen.
// Therefore, we start with manual removal of the current fragment.
removeCurrentFragment();
mFragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}
private Fragment getCurrentFragment() {
return mFragmentManager.findFragmentById(getContentFrameId());
}
private void removeCurrentFragment() {
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.remove(getCurrentFragment());
ft.commit();
// not sure it is needed; will keep it as a reminder to myself if there will be problems
// mFragmentManager.executePendingTransactions();
}
How is it possible to go back to the last Activity one has been in from a Fragment? Let's assume we've Activity A and Fragment A. I launch Fragment A from Activity A, and now I want to go back to Fragment A. When I press on the back button on my phone it closes the app.
I launch the fragment by using the FragmentManager:
Fragment fragment = new Kontakt();
getFragmentManager().beginTransaction()
.add(R.id.kontaktfrag, fragment)
.commit();
Is the solution; popBackStackImmediate() or addToBackStack() ?
Firstly try addToBackStack when adding your fragment.
then you need to override your onBackPressed function of your activity, for example:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
}
I tried myself and it worked.
try adding
getFragmentManager()
.beginTransaction()
.addToBackStack("")
.commit();
or just add .addToBackStack("") before .commit();
here is the code in your case,
Fragment fragment = new Kontakt();
getFragmentManager().beginTransaction()
.add(R.id.kontaktfrag, fragment)
.addToBackStack("")
.commit();
I want to have a Fragment which provides the ability to create someting.
After that i want to show the new "someting" in another fragment. After pressing the back button on the device i want to go back to the MainFragment and not to the CreateFragment (this works well). But after that the ShowFragment is still visible.
Here is my code:
In my MainActivity i got a MainFragment which has a button "Create".
After tap the button i load a "Create" Fragment.
fragmentManager.beginTransaction()
.replace(R.id.container, CreateFragment.newInstance())
.addToBackStack("Create")
.commit();
If the user has entered some details he taps the "Ok" Button. This fires the following on the MainActivity.
fragmentManager.beginTransaction()
.replace(R.id.container, ShowFragment.newInstance(id))
.commit();
So far so good, but here comes the problem.
If the user taps the back button on the device he gets back to the MainFragment BUT the ShowFragment is still visible (under the MainFragment).
Update
This is what happens:
MainFragment > CreateFragment > ShowFragment > (BACK Button) > MainFragment (ShowFragment in the back)
Just pop the ShowFragment from the stack on the onBackPress Event as below:
#Override
public void onBackPressed() {
final Fragment fragment = fragmentManager.findFragmentById(R.id.container);
if (fragment != null) {
fragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}
Press the back button of fragment ShowFragment within your ShowFragment fragment will call the onBackPressed() method. Then when you call method popBackStack(), it will return you back to the CreateFragment.
Sample code -
public void onBackPressed()
{
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
See the post how-to-back-to-previous-fragment-on-pressing-manually-back-button-of-indivisual-fragment for more info with similar situation.