Search code examples
javaandroidandroid-activityfragmenttoolbar

click on Back Arrow in Toolbar programmatically


hi i have an activity and I display 2 frigments I want to automatically close the toolbar when the back button is clicked

How can I do this? Should the code be written in an activity or in a fragment?

enter image description here


Solution

  • Do it in an activity:

    boolean toolbarIsOpened = false;
    
    @Override
    public void onBackPressed() {
        if (toolbarIsOpened){
            //closeToolbar
            toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
        }else{
            int count = getSupportFragmentManager().getBackStackEntryCount();
    
            if (count == 0) {
                super.onBackPressed();
            } else {
                getSupportFragmentManager().popBackStack();
            }
        }
    }
    

    Another way to hide:

    getSupportActionBar().hide();
    

    Press "back arrow" programmatically:

    onBackPressed();