Singed Singed - 1 year ago 86
Android Question

Get Toolbar's navigation icon view referrence

I would like to highlight drawer icon in my

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

Answer Source

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";
        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
        return navIcon;