Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 445
SDJSK Avatar asked May 30 '15 14:05

SDJSK


1 Answers

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);
    ...
}
like image 196
Pirdad Sakhizada Avatar answered Oct 17 '22 07:10

Pirdad Sakhizada