I have an Activity which implements OnClickListener, and I am handling onClick event as below code:
void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.xxx:
break;
}
}
and now I have a Toolbar also, So I want to handle toolbar navigation button click event in this way too:
toolbar.setNavigationOnClickListener(this);
but I don't know the id of the toolbar navigation button. How can I get it?
If the toolbar is being used as an ActionBar, the view id will be android.R.id.home
and you would use onOptionsItemSelected(...)
to know when it's pressed.
If it's not being used as an ActionBar, the view id is -1 which doesn't have a corresponding id resource defined.
Which means you must use setNavigationOnClickListener()
but in either of the two approaches:
either:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
});
or
private View.OnClickListener homeClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
};
@Override
protected void onCreate(...) {
...
toolbar.setNavigationOnClickListener(homeClickListener);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With