-1

how to quit the app whenever i press the back button from certain fragments.I found out that system.exit(1) closes the app. but i could now override method for handling back key.Is there any method to override back key ? if yes How can i perform it?

Yogesh
  • 153
  • 1
  • 12

5 Answers5

0

onBackPressed() function in activity will help

Jithin.S
  • 47
  • 1
  • 8
0

What you should do, is when you add a fragment add a tag with it, like

fragmentTransaction.replace(android.R.id.content, fragment, "My_Tag");

And then in activity onBackPressed()

fragment= (AddFriends)getFragmentManager().findFragmentByTag("My_Tag");
if (fragment!= null && fragment.isVisible()) {
   //Exit from your app here
   finish();
}

Hope this helps you.

Abdul Kawee
  • 2,687
  • 1
  • 14
  • 26
  • thanks for your answer. but i got an error on back pressed in line 1 showing inconvertible type. i had assummed that MyFragment in above code means the fragment that should be override on back press... – Yogesh May 29 '17 at 06:45
  • @YogeshGautam I dont know about your code but what you shared in comments from that i suggest changing `MyFragment` with your fragment – Abdul Kawee May 29 '17 at 06:50
0

write this in your onBackPressed()

if (fragmentManager.getBackStackEntryCount() == 1) {
        if (isPressed) {
            finish();
        } else {
            StringUtils.displayToastShort(this, "press again to exit");
            isPressed = true;
        }
} 
DINESH
  • 51
  • 7
0

Try this function for opening a fragment

public void openFragment(Fragment fragment)
{

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransac‌​tion();

fragmentTransaction.replace(R.id.fragment_container,fragment);

fragmentTransaction.commit();

}

and when you want to open a fragment call this function like this

openFragment(new AddFriends());

Using above function it will exit the app with back button press.

AbhayBohra
  • 2,047
  • 24
  • 36
0

I solved it in following way.

  1. First make a class with static integer variable(say a).
  2. Override back methods on mainActivity and choose the fragment you want to open on back pressed as per the value on static variable. [note:whenever new fragments are opened update static variable with new value and according to this value override back method on main activity]
Yogesh
  • 153
  • 1
  • 12