Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to add id to Toolbar back button?

For automated testing purposes I need to add ID to toolbar's BACK / MENU button view.

I tried to add id using getChildAt and setId but the id is still not set when I check the view hierarchy. android.R.id.home menu id does not work in my case. I need id that is set for the view when I check the view hierarchy with Layout inspector. Only then the id can be used for automated UI tests.

Could you suggest a way to do this?

like image 305
Mario Kutlev Avatar asked Sep 01 '25 18:09

Mario Kutlev


1 Answers

toolbar's BACK / MENU button has already id android.R.id.home you can use this id

to perform action on that use below code

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {
        Toast.makeText(context, "Backarrow pressed", Toast.LENGTH_SHORT).show();
        return true;
    }

    return false;
}
like image 123
AskNilesh Avatar answered Sep 04 '25 07:09

AskNilesh