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

我的梦境 提交于 2019-12-24 20:56:20

问题


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

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>

回答1:


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.



来源:https://stackoverflow.com/questions/53238957/android-how-to-add-a-default-checked-checkbox-to-navigation-drawer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!