10

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?

hata
  • 11,633
  • 6
  • 46
  • 69
SDJSK
  • 1,292
  • 17
  • 24

3 Answers3

2

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);
    ...
}
Pirdad Sakhizada
  • 608
  • 7
  • 12
1

When you Toolbar.setNavigationIcon(), the button (hamburger icon) has NO_ID.

That is why View.getId() returns -1 in the onClickLister as @Adolfok3 answered.

public int getId ()

Returns this view's identifier.

Returns

int a positive integer used to identify the view or NO_ID if the view has no ID

https://developer.android.com/reference/android/view/View#NO_ID

public static final int NO_ID

Used to mark a View that has no ID.

Constant Value: -1 (0xffffffff)

hata
  • 11,633
  • 6
  • 46
  • 69
0

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;
}
Adolfok3
  • 304
  • 3
  • 14