Resuming a previous fragment onBackPressed()? - java

I have a HomeFragment that has a button, which when clicked calls the following:
Fragment frag = new CustFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();
Then in my FragmentActivity which is the fragments mentioned above, I have:
#Override
public void onBackPressed() {
getFragmentManager().popBackStack();
super.onBackPressed();
}
That's what I've tried, but if I'm on the frag fragment and I press the back button, it doesn't go back to the last fragment (the HomeFragment). Instead, it attempts to go back to the last Activity, but since there is none (i.e. the previous activity had finish() invoked on it), it just goes to the Android Home Screen.
What am I doing wrong?
PS: If I'm being unclear, just comment below and i'll try to clarify.

Change
#Override
public void onBackPressed()
{
getFragmentManager().popBackStack();
super.onBackPressed();
}
to
#Override
public void onBackPressed()
{
if(getSupportFragmentManager().getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
super.onBackPressed();
}
and
fragmentManager.beginTransaction().replace(R.id.home_container, frag).commit();
to
fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();

Add your fragment to back stack using addToBackStack(null) like..
fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();

beginTransaction creates a new FragmentTransaction. It has a method addToBackstack. If you call it before you commit your transaction you can remove your overridden onBackPressed completely. Reference

You can use:
fragmentTransaction.addToBackStack(null);
and no need to take care of onBackPressed().
BTW in your onBackPressed() super.onBackPressed() means you are actually changing nothing.
It should have been something like:
if(currentFragmentIsCustFragment){
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
}

Related

popBackStack() returns same fragment

I want to when button clicked to return to previous fragment. This is how I create fragment:
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, statisticsSpecificStudentFragment)
.addToBackStack("StatisticsStudentOverallFragment")
.commit();
This is how I try and return to this fragment, from whom I started new fragment:
btDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
}
});
All that happends is that it reloads current fragment, like I added current one to stack but I did not.
Try
popBackStack("StatisticsStudentOverallFragment")
Or
addToBackStack(null)
and keep popBackStack() like you have it already.

How to check fragment is visible in Activity OnBackpressed

How to check fragment is visible in Activity OnBackpressed
I want to check when user click back button in Searchfragment I want to set OnBackpressed is running ,but if user click back button in OtherFragment I want to set OnBackpressed is not running.
and I try this in Activity is not work
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SearchFragment searchFragment = new SearchFragment();
if (searchFragment.isVisible()){
onBackPressed();
}
}
});
thanks for your help!
First of all, when you declare something like this:
SearchFragment searchFragment = new SearchFragment();
And then call
searchFragment.isVisible()
This will obviously return false since you didnt even add it to the container. What you need to do is to retrieve the fragment instance that you already added and check it's state.
I have once tried to use the method isVisible() but it is not entirely accurate, at least not for my case. What I came up with is to check the top fragment in the container as follow:
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(fragment instance of SearchFragment) //means your visible fragment is the SearchFragment
onBackPressed();

Implementing back stacks with fragments

I'm attempting to implement a back stack while using fragments, but when using the Back button, I keep getting taken out of the app to the home screen.
Activity opens fragment A; Fragment A has a clickable TextView that opens fragment B (this works). Hitting BACK should return me to fragment A, but it takes me to the home screen instead.
Here is the activity's call to the opening of fragment A in onCreate:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_layout_container, new FragmentLogin(), "fragment_login")
.addToBackStack("login_screen")
.commit();
Log.d("Back", getFragmentManager().getBackStackEntryCount() +" <- Entry Count at LoginActivity.onCreate" );
At this point, the Log prints 0 <- Entry Count at LoginActivity.onCreate. Something I've done wrong keeps this from printing 1.
Then, the Fragment A has this listener:
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_layout_container, new FragmentForgottenPassword(), "fragment_password")
.addToBackStack("forgotten_password")
.commit();
Log.d("Back", getFragmentManager().getBackStackEntryCount() + " <- Entry Count at FragmentLogin.onCreateView.Listener");
}
});
The Log here prints 1 <- Entry Count at FragmentLogin.onCreateView.Listener. Here, the listener works and opens fragment B - but the back button returns me to the home screen.
Use this in your Activity it should pop out the fragments already added to backstack
#Override
public void onBackPressed()
{
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Try Like This,
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.fragment_layout_container, fragment);
transaction.commitAllowingStateLoss();
getFragmentManager().executePendingTransactions();
}
and Used it like this,
replaceFragment(new FragmentForgottenPassword(), true);
There is a GitHub library that will do this work for you!https://github.com/rathodchintan/Fragment-Back-StackWhenever you are displaying any new fragment, just push that fragment into stack using following code.
//here this fragment is our first fragment
homeListFragment = new HomeListFragment();
fragmentStack.push(homeListFragment);It has many other stack options too.

How to call another fragment from one fragment on hitting back button?

I have a MainActivity in my application, from where all the fragments are called using Navigation Drawer. And default fragment of the activity is 'A'. So everytime i open the application, 'A' fragment is called. when I hit 'back' from another fragment B, I want to get to default fragment 'A', as what happens in gmail - from any fragment if we hit back, it returns to default fragment "Primary mails".
I tried calling the 'A' fragment by adding the following code to the onPause() of fragment 'B'.
#Override
public void onPause() {
super.onPause();
fragment = new A();
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.replace(R.id.a,fragment ).commit();
}
But when I hit back, fragment 'A' is called for a moment, but then the application closes unexpectedly.
Logcat :
01-14 12:44:42.264: E/WindowManager(4655): android.view.WindowLeaked: Activity com.litchi.iguardian.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41da6348 V.E..... R.....ID 0,0-513,243} that was originally added here
Whats the correct way of doing this ?
to back to previous fragment see below code :
fragmentManager.popBackStack(...);
put this in onBack event
to call popBackStack method you first need to call addToBackStack method while calling fragment
Use this code
android.support.v4.app.Fragment detail = new CurrentClass();
detail.setArguments(bundle);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.content_frame, detail).addToBackStack("back")
.commit();
You should customize the behavior when you press the back button, because by default it will destroy launched activity and you see your fragment while callbacks goes from onPause() until onStop() and activity is not visible for you anymore. Just override this method, it must solve the problem:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your code
return true;
}
return super.onKeyDown(keyCode, event);
}
But yeah, it is for global control, for switching fragments you may also call addToBackStack(); when you want return previous fragment by pressing back button.
instead of writing that code in onPause() you can write that code in onBackPressed() of your main activity .

Listen to "back" key pressed in a Fragment

I use a Fragment to let the user enter information in my Android application. If information has been entered, I want a warning to be sent to the user if he presses the "back" key. If he confirms he wants to abandon the changes, the Fragment has to be popped. If he cancels the abandon, the Fragment should remain as it is.
I already tried to implements onKeyListener to my Fragment with an onKey callback function. But it is never executed.
How can I do?
Try something like this. (I haven't been able to test this)
In your activity, override onBackPressed():
#Override
public void onBackPressed() {
Fragment frag = getSupportFragmentManager().findFragmentById(R.id.your_container);
if(frag instanceof TheFragmentYouAreTalkingAbout) {
((TheFragmentYouAreTalkingAbout)frag).showConfirmGoBackDialog();
} else {
super.onBackPressed();
}
}
The showConfirmGoBackDialog() method should create a dialog box. In this dialog you can put a listener on the confirm/OK button that will call getFragmentManager().popBackStack(); if pressed, otherwise do nothing.
I would prefer not to use instanceof comparison.
So my solution is to provide a tag when commiting fragment transaction. Then you can find fragment by tag:
private void showMyFragment(){
Fragment fragment = new MyFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, MY_FRAGMENT_TAG);
ft.commit();
}
#Override
public void onBackPressed() {
MyFragment fragment = (MyFragment)findFragmentByTag(MY_FRAGMENT_TAG);
if (fragment != null) {
fragment.showConfirmation
} else {
super.onBackPressed();
}
}

Categories