How to go back to last activity from fragment? - android

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();

Related

Navigating between two fragments on backpress

I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..
Fragment1 calling second fragment
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
In second Fragment i have implemented an interface OnBackpress and over riding the below method
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
if(getFragmentManager().findFragmentByTag("UserActivity") != null){
Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
getFragmentManager().popBackStack();
};
}
}
But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks
You need to add you first fragment to back stack properly, you are doing it wrong in your first part of the code.
Use the following code instead.
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.replace(android.R.id.content, frag, "UserActivity");
transaction.commit();
Also there is no need to add any code in your onBackPressed after above change.
First, you need to add your fragments to the backstack:
public static void addFragment(FragmentManager fragmentManager, Fragment fragment, int id){
fragmentManager.beginTransaction().add(id, fragment).addToBackStack(null).commit();
}
Then you need to override the onBackPressed, which is a method gets called whenever a user clicks the back button:
#Override
public void onBackPressed() {
super.onBackPressed();
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
button.setVisibility(View.VISIBLE);
}
}
please change to add() instead of replace() in your code..
UserFragment frag = new UserFragment()
FragmentTransaction transaction = getFragmentManager().beginTransaction();
frag.setArguments(bundle);
transaction.addToBackStack("UserActivity");
transaction.add(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
This will solve your problem.

Handle OnBackPress from Fragment

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.

Keep Android Fragments in Backstack

I'm working on android fragments and i am unable to keep the fragments in backstack i-e when i press back button it pushes me out of the Activity which starts fragments, i want to go back to previous fragment on backpress.
So far i have tried this but i am unable to keep the fragments in backstack.
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.mainContainer, searchResultsFragment)
.addToBackStack(null)
.commit();
before you call commit() to commit transaction, you should add fragment to backstack addToBackStack(null) as you did in your provided code
then override onBackPressed() to pop fragment from stack
the issue you facing , you make your transaction with FragmentManager
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.mainContainer, searchResultsFragment)
.addToBackStack(null)
.commit();
but you in onBackPressed() you using SupportFragmentManager
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ) {
getSupportFragmentManager().popBackStack();
}
}
to fix your issue , you must know what you match your fragment type (in your case searchResultsFragment) I mean if its extend Fragment or support Fragment
in case you extend fragment support
import android.support.v4.app.Fragment;
you should use getSupportFragmentManager() in both transaction and onBackPressed
in case you use fragment
import android.app.Fragment;
you should use getFragmentManager() in both transaction and onBackPressed
You have to overwrite onBackPressed in your activity. It is not enough only adding the fragment to back stack.
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
if(fragmentManager.getBackStackEntryCount() != 0) {
fragmentManager.popBackStack();
} else {
super.onBackPressed();
}
}
I just remove this line:
.addToBackStack(null)
And works for me.

Why OncreateView called in non stored fragments?

I have a MainActivity and two fragments in this activity like SignupFragment and MenuFragment.First i add SignupFragment in MainActivity:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new SignupFragment());
ft.commit();
Important: i don't need to store this fragment in backstack
Now from SignupFragment i replace MenuFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.content_frame, new MenuFragment(), FRAGMENT_TAG)
.addToBackStack(null)
.commit();
Important: i need to add this fragment to backstack.For example i have another framgent like AnotherFragment and i replace it in MenuFragment and add that to backstack too and when user in AnotherFragment pressed back button i want to return him to MenuFragment
I override OnBackPressed in MainActivity and also add a listener for OnBackStackChangeListener:
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0)
finish();
}
});
Problem When i'm in MenuFragment and press back button then i go back to SignupFragment andOnCreateView called for a little moment and then finish() called.( when i press back button , SignupFragmen's view shows for a moment and then destroyed )
Questions
1- How can i prevent to returning back to SignupFragment ?
2- Why OncreateView called in SignupFragment when back button pressed?
Thanks in advance.
I found my problem.
when i pressed back button, OnBackPressed called and also MenuFragment is visible yet then onCreateView of SignupFragment called and then onBackStackChanged called , So i check this in OnBackPressed:
if(getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG).isVisible()){
finish();
}

how to back to previous fragment on pressing manually back button

I have one activity and multiple fragments in my app. i want to back one by one fragments when pressing back button which in all fragments.
i used this code segment but when pressing back button it comes to main activity without back one by one. Also i want to change the icon when it's comes to the main activity.(msg_alert)
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = MainActivity.this
.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = new MainMenuLayout();
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
btnBack.setVisibility(View.VISIBLE);
btnBack.setImageResource(R.drawable.msg_alert);
tvTitle.setText("Layout 0");
}
});
Lets say you are having two fragments A and B. Fragment A is is attached at the startup of activity and on any user event you navigate to fragment B by replacing the Fragment A.
1) while adding Fragment B to the activity
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragmentB, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
2) override the onBackPressed of the activity to handle the back button press event.
#override
public void onBackPressed() {
// is there any fragment in backstack, if yes popout.
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
return;
}
super.onBackPressed();
}
this is one more option ,
in the Activity.
Fragment secondfragment= new SecondFragmnet();
#Override
public void onBackPressed() {
if(secondfragment.isVisible()){
// replace 1st fragment
}else{
// Alert dialog for Exit App
}
// you can check multiple fragments.
Hope it helps you
You have to Use addToBackStack() method while doing Transaction Between Fragments...
Read This : Implement Back Navigation for Fragments
Use Following code when you use Fragment Transaction...
String backStateName = fragment.getClass().getName(); // getting Fragment Name..
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment)
.addToBackStack(backStateName) //adding it to BackStack..
.commit();
In Fragments we dont have back navigation..
We can acheive that through replace() method.
I seen in your code that you are only replace the content frame. and so the result is backpress it comes to activity.
Also be sure that you have your mannual back button in the activity
this is test xml for activity
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
Use
Fragment fragment = new MainMenuLayout();
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.addToBackStack(null);// TODO parameter here it tag of fragment or null or "" String
ft.commit();
For more information about fragments backstack go through this android developer refrence :-Fragment BackStack

Categories

Resources