Search code examples
androidandroid-toolbar

OnBackBressed not called


I have activity ActivityProfile, have getSupportActionBar().setDisplayHomeAsUpEnabled(true); implemented, onBackPressed() as well, search all over the internet and still no help.

@Override
    public void onBackPressed() {
        Toast.makeText(this, "OnBackpressed fired", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //replaces the default 'Back' button action
        if(keyCode== KeyEvent.KEYCODE_BACK)   {
// something here
            onBackPressed();
        }
        return true;
    }

using the device's back button works, but not on the app...


Solution

  • hi add this code in your activity. when you press back button in toolbar following code execute.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_view);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
            default:
                return super.onOptionsItemSelected(item);
    
        }
        return super.onOptionsItemSelected(item);
    }