Подтвердить что ты не робот

Как изменить цвет текста и значков выбранного пункта меню в навигационном ящике программно с помощью java

Я новичок в Android Development. Использование активности Android-навигатора по умолчанию для Android. Я разрабатываю приложение. Одним из требований этого приложения является случайное изменение цвета фона макетов (включая цвет заголовка навигационного ящика) во время выполнения.

Теперь все будет хорошо, за исключением того, что цвет выбранного пункта меню в навигационном ящике по-прежнему остается синим. как это:

enter image description here

Теперь то, что я хочу, так как цвет фона других макетов розово, выбранный пункт меню на панели навигации также должен быть розовым (я имею в виду цвет текста и значок должен быть розовым) следующим образом:

enter image description here

Кто-нибудь может рассказать, как это сделать программно в коде, поскольку я должен случайно изменить выбранный текст и цвета значков во время выполнения.

Здесь файл 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>
4b9b3361

Ответ 1

Во-первых, спасибо всем вам за ответы на ваши решения :) Изучая приведенные выше ответы и проводя некоторые исследования ColorStateList мне наконец-то удалось создать 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);
}

вы можете вызвать этот метод с любым int color вы хотите :)

Ответ 2

Сначала проверьте 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" />

Проверьте здесь две вещи

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

Оба эти drawer_item_color.xml используют drawer_item_color.xml который является селектором в папке для рисования, и ниже приведен код для него

<?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>

используйте селектор и добавьте цвета, которые вы хотите. Это сделает работу за вас.

Ответ 3

Первый путь

попробуйте использовать:

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

Для вашего 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" />

Второй путь

Для программно меняйте использование:

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

Определите ColorStateList1 и ColorStateList2 как:

Для навигации Вид текста Цвет текста

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);

Для навигации

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);

Ответ 4

Ты пробовал?

mNavigationView.setItemTextColor(yourColorStateList);

Ответ 5

Я проверил этот код на SDK 17 код SDK 26 написать логику после

   setContent(R.layou.your_activity)

найти навигационный вид с идентификатором

 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;

}