-2

how to implement press back again to exit in android studio, Pls. see My coding here. i'd checked all discussions here regarding this, but not working with my code. i've to make sure On back pressed, always go to home fragment before closing. Thank you very much in advance!

 /**
     * On back pressed, always go to home fragment before closing
     */
    @Override
    public void onBackPressed() {
        //if stack has items left
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            //get current fragment
            Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mainFragment);

            //only close if in CategoryFragment else go to CategoryFragment
            if (fragment instanceof SearchFragment) {
                finish();
            } else {
                changeFragment(new SearchFragment());
            }
        } else {
            super.onBackPressed();
        }
    }
shriakhilc
  • 2,922
  • 2
  • 12
  • 17
Rabee
  • 1
  • 1
  • 1
    Your question, comments and code doesn't say the same. You are talking about home fragment, but based on your comment you would like to navigate to CategoryFragment, however in your code you actually navigating to SearchFragment. Please edit your question and code, otherwise we can't help you. – cylon Nov 04 '18 at 09:21
  • @cylon1. In above given code, i want to implement "press back again to exit" . I've checked this site discussion regarding this. but when inserting code for press back again to exit toast ,it's not working. My above code is only to go category fragment before closing. Thank you very much – Rabee Nov 04 '18 at 10:30

2 Answers2

0

OnBackPress

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish()
Sz-Nika Janos
  • 811
  • 6
  • 19
0

If you wanna make onBackPressed again to exit activity you can use this

public void onBackPressed() {
    count++;
    if (count > 1) {
        moveTaskToBack(true);
    } else {
        showToast("Press back again to Leave!");

        // resetting the counter in 2s
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                count = 0;
            }
        }, 2000);
    }
}