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

前端 未结 5 991
栀梦
栀梦 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:44

    Firstly thank you all for responding back with your solutions :) Learning from the answers above and doing some research on ColorStateList I finally managed to create a method which sets the color of the checked item on the navigation drawer to match the color of my app theme color which is generated randomly at runtime.

    Here's the method:

    public void setNavMenuItemThemeColors(int color){
        //Setting default colors for menu item Text and Icon
        int navDefaultTextColor = Color.parseColor("#202020");
        int navDefaultIconColor = Color.parseColor("#737373");
    
        //Defining ColorStateList for menu item Text
        ColorStateList navMenuTextList = new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{android.R.attr.state_enabled},
                        new int[]{android.R.attr.state_pressed},
                        new int[]{android.R.attr.state_focused},
                        new int[]{android.R.attr.state_pressed}
                },
                new int[] {
                        color,
                        navDefaultTextColor,
                        navDefaultTextColor,
                        navDefaultTextColor,
                        navDefaultTextColor
                }
        );
    
        //Defining ColorStateList for menu item Icon
        ColorStateList navMenuIconList = new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{android.R.attr.state_enabled},
                        new int[]{android.R.attr.state_pressed},
                        new int[]{android.R.attr.state_focused},
                        new int[]{android.R.attr.state_pressed}
                },
                new int[] {
                        color,
                        navDefaultIconColor,
                        navDefaultIconColor,
                        navDefaultIconColor,
                        navDefaultIconColor
                }
        );
    
        mNavView.setItemTextColor(navMenuTextList);
        mNavView.setItemIconTintList(navMenuIconList);
    }
    

    you can call this method with any int color you want :)

提交回复
热议问题