简体   繁体   中英

back press on fragment finishing activity

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

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

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();

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM