Android Toolbar Navigation Button Id

I have an activity that implements OnClickListener, and I am handling the onclick event, as shown below:

void onClick(View v){ final int id = v.getId(); switch(id){ case R.id.xxx: break; } } 

and now I have a toolbar, so I also want to handle the event of clicking the navigation button on the toolbar:

 toolbar.setNavigationOnClickListener(this); 

but I don’t know the identifier of the navigation button on the toolbar. How can i get it?

+7
android toolbar
source share
2 answers

If the toolbar is used as an ActionBar, the view identifier will be android.R.id.home , and you would use onOptionsItemSelected(...) to know when it is clicked.

If it is not used as an ActionBar, the view identifier is -1, which does not have a specific identifier resource.

This means that you must use setNavigationOnClickListener() , but in either of two approaches:

or:

  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); ... } 
0
source share

Just print a log to get an identifier, for example: Log.w("ID: ", ""+v.getId()); In my case there was a -1 value.

 switch(id) { case -1: break; } 
0
source share

All Articles