Checking Default Item In Menu Group Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Checking Default Item In Menu Group without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

We are here to answer your question about Checking Default Item In Menu Group - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji