Search code examples
androidandroid-actionbarnavigation-drawertoolbarhamburger-menu

Get Toolbar's navigation icon view reference


I would like to highlight drawer icon in my Toolbar (working on a tutorial). For that, I need its position. How do I get a reference to drawer's navigation icon (hamburger) view?


Solution

  • You can make use of content description of the view and then use findViewWithText() method to get view reference

     public static View getToolbarNavigationIcon(Toolbar toolbar){
            //check if contentDescription previously was set
            boolean hadContentDescription = !TextUtils.isEmpty(toolbar.getNavigationContentDescription());
            String contentDescription = hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
            toolbar.setNavigationContentDescription(contentDescription);
            ArrayList<View> potentialViews = new ArrayList<View>();
            //find the view based on it's content description, set programatically or with android:contentDescription
            toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
            //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence 
            View navIcon = null;
            if(potentialViews.size() > 0){
                navIcon = potentialViews.get(0); //navigation icon is ImageButton
            }
             //Clear content description if not previously present
            if(!hadContentDescription)
                toolbar.setNavigationContentDescription(null);
            return navIcon;
         }
    

    More

    Kotlin extension property:

    val Toolbar.navigationIconView: View?
            get() {
                //check if contentDescription previously was set
                val hadContentDescription = !TextUtils.isEmpty(navigationContentDescription)
                val contentDescription = if (hadContentDescription) navigationContentDescription else "navigationIcon"
                navigationContentDescription = contentDescription
                val potentialViews = arrayListOf<View>()
                //find the view based on it's content description, set programatically or with android:contentDescription
                findViewsWithText(potentialViews, contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
                //Clear content description if not previously present
                if (!hadContentDescription) {
                    navigationContentDescription = null
                }
                //Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
                return potentialViews.firstOrNull()
            }