Не выделять выбранный дочерний элемент из навигации

У меня есть NavigationView и меню рендеринга внутри него. Мое меню состоит из 3 групп, каждая из которых содержит несколько пунктов подменю. Моя проблема в том, что когда я выбираю любой элемент подменю и перехожу к определенному фрагменту. Однако, когда я снова открываю NavigationView/drawer, чтобы выбрать другой элемент, последний выбранный элемент не отображается выделенным.

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

введите здесь описание изображения

XML-код базовой активности

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_app_base"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <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"
        app:headerLayout="@layout/nav_header_app_base"
        app:menu="@menu/activity_app_base_drawer"
        android:background="@color/white"
        app:itemBackground="@color/white" />

</android.support.v4.widget.DrawerLayout>

XML пунктов меню (activity_app_base_drawer)

<item
    android:id="@+id/nav_android_title"
    android:title="Android" >
    <menu>
        <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_android_best_practices"
            android:icon="@drawable/best_practices_icon"
            android:checked="false"
            android:title="Best Practices" />
        <item
            android:id="@+id/nav_android_monthly_report"
            android:icon="@drawable/report_icon"
            android:checked="false"
            android:title="Monthly Report" />
        </group>
    </menu>
</item>
<item
    android:id="@+id/nav_iOS_title"
    android:title="iOS">
    <menu>
        <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_ios_best_practices"
            android:icon="@drawable/best_practices_icon"
            android:checked="false"
            android:title="Best Practices" />
        <item
            android:id="@+id/nav_ios_monthly_report"
            android:icon="@drawable/report_icon"
            android:checked="false"
            android:title="Monthly Report" />
        </group>
    </menu>
</item>
<item
    android:id="@+id/nav_communicate_title"
    android:title="Other">
    <menu>
        <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_terms"
            android:icon="@drawable/terms_icon"
            android:checked="false"
            android:title="Terms &amp; Conditions" />
        <item
            android:id="@+id/nav_about_us"
            android:icon="@drawable/about_icon"
            android:checked="false"
            android:title="About Us" />
        </group>
    </menu>
</item>


comment
сгруппируйте родительское меню так же, как дочернее   -  person Rajesh    schedule 04.01.2017
comment
Если вы хотите проверить элемент, просто установите checkable перед установкой проверенного состояния. item.setCheckable(true); item.setChecked(true);   -  person Harshad Pansuriya    schedule 04.01.2017
comment
@RajeshKushvaha Не сработало   -  person VVB    schedule 04.01.2017
comment
@Ironman Уже пробовал, но не работает   -  person VVB    schedule 04.01.2017
comment
@VVB просто измените так android:checkable="true" для всех Item.   -  person Harshad Pansuriya    schedule 04.01.2017
comment
@Ironman выше ничего не работало   -  person VVB    schedule 04.01.2017


Ответы (2)


Вот идеальный код!

Добавьте три атрибута в NavigationView

приложение:itemIconTint
приложение:itemTextColor
приложение:itemBackground

<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"
    app:headerLayout="@layout/nav_header_app_base"
    app:menu="@menu/activity_app_base_drawer"
    android:background="@color/white"
    app:itemIconTint="@drawable/navigation_view_icon_tint_selector"
    app:itemTextColor="@drawable/navigation_view_text_selector"
    app:itemBackground="@drawable/ripple_navigation_selector"
 />

navigation_view_icon_tint_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- This is used when the Navigation Item is checked -->
<item android:color="#005481" android:state_checked="true" />
<item android:color="#005481" android:state_pressed="true"></item>
<item android:color="#005481" android:state_activated="true"></item>
<!-- This is the default text color -->
<item android:color="#525252" />

navigation_view_text_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- This is used when the Navigation Item is checked -->
<item android:color="#005481" android:state_checked="true" />
<item android:color="#005481" android:state_pressed="true"></item>
<item android:color="#005481" android:state_activated="true"></item>
<!-- This is the default text color -->
<item android:color="#525252" />

ripple_navigation_selector

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#ffdbdb" android:state_pressed="true"/>
<item android:drawable="#ffdbdb" android:state_activated="true"/>
<item android:drawable="#ffdbdb" android:state_checked="true"/>
<item android:drawable="#FFFFFF"/>

person Kishore Jethava    schedule 04.01.2017
comment
Отлично работает. Большое спасибо. Продолжайте в том же духе. Требуется только изменение, чтобы передать @color/color_name вместо жестко закодированного, так как это дает ошибку для атрибута drawable - person VVB; 04.01.2017
comment
действительно <item android:drawable="#ffdbdbdb" ? - person VLeonovs; 21.06.2018

Вы можете определить проверяемое поведение для отдельных пунктов меню с помощью атрибута android:checkable в элементе или для всей группы с помощью атрибута android:checkableBehavior в элементе. Поэтому добавьте checkableBehavior для главного меню.

<menu>
<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_android_title"
        android:title="Android" >
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:id="@+id/nav_android_best_practices"
                    android:icon="@drawable/best_practices_icon"
                    android:checked="false"
                    android:title="Best Practices" />
                <item
                    android:id="@+id/nav_android_monthly_report"
                    android:icon="@drawable/report_icon"
                    android:checked="false"
                    android:title="Monthly Report" />
            </group>
        </menu>
    </item>
    <item
        android:id="@+id/nav_iOS_title"
        android:title="iOS">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:id="@+id/nav_ios_best_practices"
                    android:icon="@drawable/best_practices_icon"
                    android:checked="false"
                    android:title="Best Practices" />
                <item
                    android:id="@+id/nav_ios_monthly_report"
                    android:icon="@drawable/report_icon"
                    android:checked="false"
                    android:title="Monthly Report" />
            </group>
        </menu>
    </item>
    <item
        android:id="@+id/nav_communicate_title"
        android:title="Other">
        <menu>
            <group android:checkableBehavior="single">
                <item
                    android:id="@+id/nav_terms"
                    android:icon="@drawable/terms_icon"
                    android:checked="false"
                    android:title="Terms &amp; Conditions" />
                <item
                    android:id="@+id/nav_about_us"
                    android:icon="@drawable/about_icon"
                    android:checked="false"
                    android:title="About Us" />
            </group>
        </menu>
    </item>
</group>
</menu>
person Anjal Saneen    schedule 04.01.2017
comment
Спасибо, но ничего не произошло. Это то же самое, что и предыдущий - person VVB; 04.01.2017