1

I have an activity with fragments that it navigates too. When you hit back on the fragment it should return back to the activity. But when you hit back at the moment the app closes.

Now thats not totally undesired behaviour as I would like the app to close when you hit back on the main activity.

Code on main activity that does this:

@Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();

            this.finishAffinity();
        }
    }

There is no onBackPressed method on the fragment

How can I make this so that when you hit back on the fragment the main activity shows but when you hit back on the activity the app closes

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Lewis Smith
  • 1,271
  • 1
  • 14
  • 39

2 Answers2

2

Use it something like this

for API level 5 and greater

@Override
public void onBackPressed() {
  super.onBackPressed()
if (keycode == KeyEvent.KEYCODE_BACK) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                finish();
            }
}

older than API 5

 public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_BACK) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                finish();
            }
        }
        return super.onKeyDown(keycode, event);
    }

Let me know if it works for you

Sandeep Parish
  • 1,888
  • 2
  • 9
  • 20
1

Remove this.finishAffinity(); from onBackPressed()

SAMPLE CODE

@Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
            finish();

        }
    }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • But if I remove that and hit back it goes to a white screen – Lewis Smith Jun 15 '18 at 09:27
  • @LewisSmith check this https://stackoverflow.com/questions/23293245/handling-fragment-back-stack-with-navigation-drawer and this https://stackoverflow.com/a/21093352/7666442 – AskNilesh Jun 15 '18 at 09:30