how to override action bar back button in android?

前端 未结 10 709
孤街浪徒
孤街浪徒 2020-11-30 03:40

I want to customize the activity back button in action bar, not in hard key back button. I have overriden the onBackPressed() method. It works with my emulator

10条回答
  •  既然无缘
    2020-11-30 04:20

    Two things to keep in mind that the user can either press back button or press the actionbar home button.
    So, if you want to redirect him to the same destination then you can do this.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return false;
    }
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
        startActivity(intent);
        finish();
    }
    

    This will take the user to the intent pressing either key or the action bar button.

提交回复
热议问题