Search code examples
javaandroidandroid-activityandroid-studioback-button

Override back button event of top menu issue in Android


I want to back to previous activity from the current activity.

So I added this code to the current activity

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //super.onBackPressed();
            //NavUtils.navigateUpFromSameTask(this);
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

But it doesn't fires at all.

What do I am missing?


Solution

  • Override the onOptionsItemSelected() method in your Activity :

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: // the default resource ID of the actionBar's back button
                Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
                break;
        }
    
        return true;
    }
    

    You get the clicked menu item id using item.getItemId(), then you check if it's equal to android.R.id.home, the default resource ID of the actionBar's back button.

    The FLAG_ACTIVITY_CLEAR_TASK flag finishes all the old activities.