How to change the text and icon color of selected menu item on Navigation Drawer programmatically using java

前端 未结 5 984
栀梦
栀梦 2020-12-14 01:44

I am a beginner in Android Development. Using android\'s default Navigation drawer activity I am developing an application. One of the requirements of this app is to change

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 02:40

    I have tested this code on sdk 17 to sdk 26 code write the logic after

       setContent(R.layou.your_activity)
    

    find the navigation view with Id

     private void setupNavigationSelection(NavigationView navigationViewList) {
    
    
        /* note : warning don't use other attribute  just checked and unchecked else         wont work*/
        int[][] states = new int[][]{
                new int[]{android.R.attr.state_checked}, // checked
                new int[]{-android.R.attr.state_checked} // unchecked
        };
        int[] colors = new int[]{
                Color.RED
                Color.GREEN,
        };
    
        LayerDrawable layerDrawable = getSideBarDrawable(0x80dedede);
        StateListDrawable arrowImgStates = new StateListDrawable();
        Drawable normalDrawable = new ColorDrawable(Color.TRANSPARENT);;
        arrowImgStates.addState(new int[]{android.R.attr.state_pressed}, normalDrawable);
        arrowImgStates.addState(new int[]{android.R.attr.state_focused}, layerDrawable);
        arrowImgStates.addState(new int[]{android.R.attr.state_selected}, layerDrawable);
        arrowImgStates.addState(new int[]{android.R.attr.state_checked}, layerDrawable);
        arrowImgStates.addState(new int[]{}, normalDrawable);
    
        ColorStateList colorStateList = new ColorStateList(states, colors);
        navigationViewList.setItemTextColor(colorStateList);
        navigationViewList.setItemIconTintList(colorStateList);
        navigationViewList.setItemBackground(arrowImgStates);
    
    }
    
    public LayerDrawable getSideBarDrawable(int bgColor) {
        int iSize = CLViewUtil.dpToPx(6);
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setShape(GradientDrawable.RECTANGLE);
        gradientDrawable.setStroke(iSize, CLThemeUtil.getThemePrimaryColor(this));
        gradientDrawable.setColor(bgColor);
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{gradientDrawable});
        layerDrawable.setLayerInset(0, 0, -iSize, -iSize, -iSize);
        return layerDrawable;
    
    }
    

提交回复
热议问题