6

When using the new Toolbar with the appcompat support library, it seems to me that the Home button doesn't work as it used to be unless you set a valid options menu. A simple and bog standard activity:

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() will be called all right with android.R.id.home and all is fine. However, if there is no onCreateOptionsMenu() at all (or it's empty, either returning trueor calling the super function), onOptionsItemSelected() won't be called at all, thus there is no chance to catch the click on the Home button. I even tried to pass an empty menu to onCreateOptionsMenu() but it didn't help.

Is there a workaround that allows us to have a working Home button on pages that don't need a functional options menu?

1

1 Answer 1

-1

You can try this..

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

Hope it will help you..

Not the answer you're looking for? Browse other questions tagged or ask your own question.