How to get the ID of Toolbar's Navigation Button?
Asked Answered
I

3

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?

Impending answered 30/5, 2015 at 14:29 Comment(3)
You can handle Toolbar menu clicks inside the onOptionsItemSelected() method.Bose
you can try to add on click method directly to toolbar also which can help you, and for your above situation for home button id is android.R.id.homeTyrannicide
did you get an appropriate answer to this ? I am trying to achieve the samePolyp
D
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);
    ...
}
Desulphurize answered 23/10, 2016 at 4:4 Comment(0)
T
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)

Tsunami answered 27/6, 2021 at 9:6 Comment(0)
V
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;
}
Vazquez answered 22/11, 2017 at 17:3 Comment(2)
Could you explain the code and its changes to make it useful to future readers?Floor
is the toolbar navigation button id. Just print a log to get the id, like: Log.w("ID: ", ""+v.getId());Vazquez

© 2022 - 2024 — McMap. All rights reserved.