Nikhil Wagh
Nikhil Wagh

Reputation: 1498

Android - How to add a default checked CheckBox to Navigation Drawer

I want to add a check box to Navigation Drawer, and I want one of them to be default checked

I'm using this: app:actionViewClass="android.widget.Switch" as suggested in this answer.

But I couldn't figure out how to make one of them default checked. If I use this property android:checked="true", then the option is checked instead of checkbox (See image).

enter image description here

Does anyone know how to make it default checked (if possible, I want to do it in XML only)?

Here is my activity_drawer.xml.

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

    <group
        android:checkableBehavior="single">
        <item
            android:id="@+id/checkboxX-axis"
            android:title="Show x-axis"
            android:icon="@drawable/ic_x_axis_black_24dp"
            app:actionViewClass="android.widget.CheckBox"
            android:checked="true"
            />
        <item
            android:id="@+id/checkboxY-axis"
            android:title="Show y-axis"
            android:icon="@drawable/ic_y_axis_black_24dp"
            app:actionViewClass="android.widget.CheckBox"
            />
        <item
            android:id="@+id/checkboxZ-axis"
            android:title="Show z-axis"
            android:icon="@drawable/ic_z_axis_black_24dp"
            app:actionViewClass="android.widget.CheckBox"
            />
    </group>
</menu>

Upvotes: 0

Views: 515

Answers (1)

forpas
forpas

Reputation: 164099

You can do this:

MenuItem item = navigation.getMenu().findItem(R.id.checkboxX-axis);
CompoundButton compoundButton = (CompoundButton) item.getActionView();
compoundButton.setChecked(true);

replace navigation with the NavigationView's name.

Upvotes: 1

Related Questions