问题
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