Search code examples
androidandroid-toolbar

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?


Solution

  • I could add id to the toolbar back button by searching for AppCompatImageButton and setting the id of the first found view. It's important to do this after the setup of the actionBar.

    private void addIdToBackButton() {
         for (int i = 0; i < toolbar.getChildCount(); i++) {
            View child = toolbar.getChildAt(i);
            if (child instanceof AppCompatImageButton) {
                child.setId(R.id.toolbar_back_button);
                return;
            }
         }
     }
    
    private void setUpActionBar() {
        setSupportActionBar(toolbar);
    
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Title");
        actionBar.setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(__ -> onBackPressed());
    
        addIdToBackButton();
    }