The home toolbar button does not work if there is no options menu

When using the new Toolbar with the appcompat support library, it seems to me that the Home button does not work as before, unless you set a valid options menu. Simple and marsh standard activities:

 public class MyActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.some_page); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar bar = getSupportActionBar(); bar.setHomeButtonEnabled(true); bar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.some_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed() or finish() or whatever(); break; } return super.onOptionsItemSelected(item); } } 

If there is a menu set in onCreateOptionsMenu() , onOptionsItemSelected() everything will be called correctly using android.R.id.home , and everything will be fine. However, if there is no onCreateOptionsMenu() (either it is empty, either returns true , or the super function is called), onOptionsItemSelected() will not be called at all, so there is no way to catch a click on the Home button. I even tried passing an empty menu to onCreateOptionsMenu() , but that didn't help.

Is there a workaround that allows us to have a valid Home button on pages that do not need a menu of functional options?

+6
source share
1 answer

You can try this.

 toolbar.setNavigationOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent =new Intent(Context,<Destination activity); startActivity(intent); } }); 

Hope this helps you.

0
source

Source: https://habr.com/ru/post/980590/


All Articles