简体   繁体   English

如何使用java以编程方式更改导航抽屉上所选菜单项的文本和图标颜色

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

I am a beginner in Android Development. 我是Android开发的初学者。 Using android's default Navigation drawer activity I am developing an application. 使用android的默认导航抽屉活动我正在开发一个应用程序。 One of the requirements of this app is to change the background colors of layouts (including navigation drawer header color) randomly at run time. 此应用程序的一个要求是在运行时随机更改布局的背景颜色(包括导航抽屉标题颜色)。

Now everything is going fine except the color of the selected menu item on navigation drawer is still blue . 现在一切都很顺利,除了导航抽屉上所选菜单项的颜色仍为蓝色 like this : 像这样 :

在此输入图像描述

Now what I want is as the background color of other layouts is pink the selected menu item on the navigation bar should also be pink (I mean the text color and the icon should be pink) like this : 现在我想要的是因为其他布局的背景颜色是粉红色,导航栏上的所选菜单项也应该是粉红色(我的意思是文本颜色和图标应该是粉红色),如下所示:

在此输入图像描述

Can anyone please tell how to achieve it programatically in code as I have to change selected text and icon colors at runtime randomly. 任何人都可以告诉如何在代码中以编程方式实现它,因为我必须在运行时随机更改所选的文本和图标颜色。

Here's the menu xml file for reference: 这是菜单xml文件供参考:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">


    <group android:checkableBehavior="single">
        <item
                android:id="@+id/nav_quiz_all"
                android:icon="@drawable/ic_public_black_24dp"
                android:checked="true"
                android:title="All Countries Quiz"/>
        <item
                android:id="@+id/nav_quiz_bookmarked"
                android:icon="@drawable/ic_favorite_black_24dp"
                android:title="Favorite Quiz"/>
    </group>


    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_rate"
                android:icon="@drawable/ic_star_black_24dp"
                android:title="Rate this app"/>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_share_black_24dp"
                android:title="Share"/>
            <item
                android:id="@+id/nav_feedback"
                android:icon="@drawable/ic_feedback_black_24dp"
                android:title="Feedback"/>
            <item
                android:id="@+id/nav_about"
                android:icon="@drawable/ic_info_black_24dp"
                android:title="About"/>
        </menu>
    </item>


    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="Settings"/>

</menu>

First check for the NavigationView below 首先检查下面的NavigationView

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/white"
        app:itemIconTint="@drawable/drawer_item_color"
        app:itemTextColor="@drawable/drawer_item_color"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

Check here two things 检查两件事

app:itemIconTint="@drawable/drawer_item_color"
app:itemTextColor="@drawable/drawer_item_color"

These both tags are using drawer_item_color.xml which is a selector in drawable folder and below is the code for it 这两个标签都使用了drawer_item_color.xml ,它是drawable文件夹中的选择器,下面是它的代码

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/pink" android:state_checked="true" />
    <item android:color="@color/black" />
</selector>

use selector and add colors you want. 使用选择器并添加所需的颜色。 This will do the job for you. 这将为您完成这项工作。

First Way 第一道路

try using: 尝试使用:

app:itemIconTint="@color/color_pink"  //selected icon color
app:itemTextColor="@color/color_pink" //selected text color
app:itemBackground="@color/color_gray" 

For your NavigationView 对于您的NavigationView

<android.support.design.widget.NavigationView
android:id="@+id/navigation_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/header_layout"
app:itemIconTint="@color/color_pink"  
app:itemTextColor="@color/color_pink" 
app:itemBackground="@color/color_gray"
app:menu="@menu/menu_drawer" />

Second Way 第二种方式

For programetically change use: 对于程序改变使用:

navigationView.setItemTextColor(ColorStateList1);
navigationView.setItemIconTintList(ColorStateList2);

Define ColorStateList1 and ColorStateList2 as: ColorStateList1ColorStateList2定义为:

For Navigation View Item Text Color 用于导航查看项目文本颜色

int[][] state = new int[][] {
        new int[] {-android.R.attr.state_enabled}, // disabled
        new int[] {android.R.attr.state_enabled}, // enabled
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_pressed}  // pressed

};

int[] color = new int[] {
        Color.WHITE,
        Color.BLUE,
        Color.WHITE,
        Color.WHITE
};

ColorStateList ColorStateList1 = new ColorStateList(state, color);

For Navigation View Item Icon Color 用于导航视图项目图标颜色

int[][] states = new int[][] {
        new int[] {-android.R.attr.state_enabled}, // disabled
        new int[] {android.R.attr.state_enabled}, // enabled
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_pressed}  // pressed

};

int[] colors = new int[] {
        Color.WHITE,
        Color.BLUE,
        Color.WHITE,
        Color.WHITE
};

ColorStateList ColorStateList2 = new ColorStateList(states, colors);

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. 首先感谢大家回复你的解决方案:)从上面的答案中学习并对ColorStateList进行一些研究我终于设法创建了一个method ,用于设置导航抽屉上已检查项目的颜色以匹配我的应用主题的颜色在运行时随机生成的颜色。

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 :) 你可以用你想要的任何int color调用这个方法:)

I have tested this code on sdk 17 to sdk 26 code write the logic after 我已经在sdk 17上测试了这段代码到sdk 26之后的代码写入逻辑

   setContent(R.layou.your_activity)

find the navigation view with Id 找到带有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;

}

你有没有尝试过?

mNavigationView.setItemTextColor(yourColorStateList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM