Exit from App only from the 1st fragment using onBackPressed - android

I have my MainActivity which has 6 fragments in the Navigation Drawer. Now, whenever I am in any of the 6 fragments and if I press back button, my app is exiting. I want to exit only from the 1st fragment. If I am in other fragments, then if I press back, I want it to come to the 1st fragment and from there if I press back again, then I want to exit.
I have to replace the fragments to the 1st fragment when it is not in the 1st position. I know that. But how exactly can I implement the whole in onBackPressed ?
Please help !! Thanks in advance.

override the onBackPress method and add this code;
public void onBackPressed(){
int count = getFragmentManager().getBackStackEntryCount(); // if stack count is 0, it means no fragment left to pop back stack
if (count = 0) {
finish();
}
}

You can get the fragment name with the instance and we can check weather it is in home fragment or not. Paste this code in the onBackPressed method in main activity class.
Fragment f = getSupportFragmentManager().findFragmentById(R.id.frame_container);
/**
* Compare the instances based on fragment name to change the action bar
*/
if (f instanceof HomeFragment) {
finish();
System.exit(0);
} else {
super.onBackPressed();
}

Related

Is there a way to exploite the buttom navigation bar in my mobile (previous,home) in my android app so that i don't have to create a cutomized one

I'm setting a new android app, and I want to exploit the bottom navigation bar in my phone (previous,home) so that i don't have to create a customized one, I want to know if it is possible to set an onClickEvent on these buttons
You have to handle both button separately.
For hardware back button (Previous) you have to override onBackPress method in your Activity class. So, you will get the back press event you can change the behavior of back button if you don't want back event just remove super.onBackPress(). If you want to do this from fragment you just need to add your logic like you can get current fragment instance from FragmentManager like below and call fragment method what ever you want to do on that fragment.
\\ To get current fragment
\\ NOTE: I add back stack name as class name.
public static Fragment getCurrentFragment(FragmentManager fragmentManager) {
int count = fragmentManager.getBackStackEntryCount();
if (count > 0) {
FragmentManager.BackStackEntry backStackEntry = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1);
String tag = backStackEntry.getName();
return fragmentManager.findFragmentByTag(tag);
}
return null;
}
#Override
public void onBackPressed() {
// enter code here
super.onBackPressed(); // Remove this line if you don't want to go back.
}
For home button handling you can use this answer or this post.
Please comment me if you have more questions.

removing all fragments so that onBackPressed closes app

I currently have an android app that flows A -> B -> C -> D Launched in activity 1.
After D, I have activity 2 start and the following code runs to remove all fragments from the stack.
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
My problem is that when I return to activity 1 from activity 2, is that when I press the back key Fragment C animates back to screen. Fragment D does remove but A B C do not. I would like the app to close on backpress from activity 1.
I attached the code that removes my fragments here. Debugging shows that fragment does change with each loop.
Can anyone advise what is happening here?
You can overwrite backpressed method and close the app, like this:
#Override
public void onBackPressed() {
finish(); // finish activity
}

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.

Replace fragment of one viewpager with fragment of another viewpager in the same activity back key pressed

I have 2 viewpagers: swipeViewPager and nonSwipeViewPager in MainActivity
In swipeableViewPager, I have fragments: homeFragmentFirst and homeFragmentSecond
In nonSwipeableViewPager, I have fragments: AppleFragment , MangoFragment, GrapesFragment and CherryFragment
First I want swipeableViewPager to be viewed in MainActivity. So I have set setVisibility of nonSwipeableViewPager as GONE.
After selecting an item from the drawer, I setVisibility of swipeableViewPager as GONE and of nonSwipeableViewPager as Visible.
By this, I open AppleFragment
Situation:
Suppose, I selected Grapes from drawer, GrapesFragment opens.
I do my some stuff there. And then when I press back button, the app closes i.e. the MainActivity closes.
What I want is when back button is pressed, I want to again bring back homeFragmentFirst from swipeableViewPager.
I have tried below code in GrapesFragment
#Override
public void onBackPressed() {
super.onBackPressed();
// Do some operations here
MainActivity mainActivity = new MainActivity();
mainActivity.swipeHomeViewPager.setVisibility(View.VISIBLE);
mainActivity.nonSwipeHomeViewPager.setVisibility(View.GONE);
}
I solved it myself. I added following in MainActivity:
#Override
public void onBackPressed() {
if (nonSwipeHomeViewPager.getVisibility() == View.VISIBLE) {
nonSwipeHomeViewPager.setVisibility(View.GONE);
swipeHomeViewPager.setVisibility(View.VISIBLE);
swipeHomeViewPager.setCurrentItem(0,true);
} else if (swipeHomeViewPager.getVisibility() == View.VISIBLE){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
You can implement backstack for the fragments (while adding / replacing fragment) add it to backstack. the back press will automatically take you to previous fragment.
otherwise you need to override OnBackPressed method to handle with your own logic.

Back from fragment to Activity onBackPressed

My question is that, i've one activity and one fragment,from activity open that fragment but when i pressed back button it close application.
i try with this code.
for open fragment.
case R.id.button_contact:
Fragment fragment = new FragmentContact();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).addToBackStack("Frag1").commit();
break;
for back button.
#Override
public void onBackPressed() {
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
super.onBackPressed();
}
I'm assuming you just want to remove the fragment and have the activity remain?
In that case modify your onBackPressed method to be
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("Frag1") != null) {
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
} else {
super.onBackPressed();
}
}
This will remove the fragment from the activity if it is added and if it isn't, then the back button will act as normal and destroy the activity.
Just remove this line from onBackPressed().
getSupportFragmentManager().popBackStackImmediate("Frag1",0);
Its work.
You can do something like this. It will work with your stack:
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
This piece of code will pop the stack if there is any fragment. Otherwise the back button will close the activity
What these two lines are doing:
1). getSupportFragmentManager().popBackStackImmediate("Frag1",0);
As you are adding you fragment in activity backstack, so when you are calling on back press,
it remove fragment from stack, now in your stack activity is left, means stack size is one.
2). super.onBackPressed();
I think you are aware of calling super.onbackpress funcionality, here it will finish
your activity and stack size is 0 now, and app will close immidately if stack size is 0.
so you have to remove super.onbackpress() Method.

Categories

Resources