Android Toolbar with both home and back button

2019-04-06 09:36发布

问题:

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()

回答1:

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));
    } 


回答2:

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;
        }
    });


回答3:

  1. Design our custom layout as a separate "toolbar_content.xml" and include this layout inside toolbar tag in your "main_layout.xml".
  2. Write click listeners for your items in "toolbar_content.xml" in your base activity so that listeners will be available thru out the app.