Checking Default Item In Menu Group

I am trying to check a default item in a menu group. I am not changing anything in the menu using code.

The menu is as follows:

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

<item android:title="Map type">
    <menu>
        <group
            android:checkableBehavior="single"
            >
            <item
                android:id="@+id/nav_map_type_normal"
                android:title="Normal"
                android:checked="true"
                />
            <item
                android:id="@+id/nav_map_type_satellite"
                android:title="Satellite"
                />
            <item
                android:id="@+id/nav_map_type_terrain"
                android:title="Terrain"
                />
            <item
                android:id="@+id/nav_map_type_hybrid"
                android:title="Hybrid"
                />
        </group>
    </menu>
</item>

<item
    android:id="@+id/nav_toggle_traffic"
    android:title="Toggle traffic"
    />

<item
    android:id="@+id/nav_settings"
    android:icon="@drawable/ic_settings"
    android:title="@string/action_settings"
    android:orderInCategory="100"
    />

</menu>

When the menu is first displayed, the first item (Normal) is highlighted to indicate it is checked. This is what I want to happen. I then want the highlighting to move through the group as each item is pressed.

The problem is:

  • If I press Satellite, BOTH Normal and Satellite are highlighted

    If I then press Hybrid, Normal remains highlighted, Hybrid is highlighted and Satellite reverts to its unchecked state.

Only after actually pressing Normal does its checked state behave as it should.

I have tried removing the android:checked=”true” and using performIdentifierAction in code, but this did not change the checked state.

Answer

Sorry, I forgot to mention that the menu is used in a NavigationView and as it it turns out that changes everything.

navigationView.setCheckedItem(R.id.nav_map_type_normal);

performs exactly the way I want. I found it in a comment here Navigation drawer: How do I set the selected item at startup?

Leave a Reply

Your email address will not be published. Required fields are marked *