简体   繁体   中英

android toolbar navigation button id

I have a 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);
    ...
}

Just print a log to get the id, like: Log.w("ID: ", ""+v.getId()); In my case was -1 value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM