Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Toolbar with both home and back button

Is it possible to display both home icon and back icon in the toolbar? 1) Is it possible change the order of display of back button icon and home icon. Currently it displays the arrow button first and then the logo (home button)

2) Second requirement is to clear the activity stack on clicking the home icon and going back to previous screen in case of back button.

I have the following code which will display a arrow back key and home icon which is set as logo. Is it possible to handle click events on both these icons:

Toolbar toolbar = (Toolbar)findByViewID(R.id.toolbar);
toolbar.setNavigationIcon(R.drwable.btn_back);
setSuppportActionBar(toolbar);
getSupportActionBar().setLogo(R.drawable.home_icon);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

I am able to handle to the click on arrow icon by handling it in onOptionsITemSelected method. Is there a way to handle click on logo icon? My idea is to use the home button click to clear the stack of activities and use the back button to navigate back to previous screen.

I tried with

toolbar.setNavigationOnClickListener() 

but it has no effect on back button click.

Handling android.R.id.home works when handled in

onOptionsItemSelected()
like image 593
Satish Navada Avatar asked May 24 '15 04:05

Satish Navada


2 Answers

For navigating back. This worked for me.

@Override 
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                Intent homeIntent = new Intent(this, HomeActivity.class);
                homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(homeIntent);
        } 
        return (super.onOptionsItemSelected(menuItem));
    } 
like image 175
Vinay Avatar answered Sep 17 '22 17:09

Vinay


try with this

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
                getActivity().finish();
            }
            return true;
        }
    });
like image 29
Son Nguyen Thanh Avatar answered Sep 17 '22 17:09

Son Nguyen Thanh