Home > Mobile >  Android Checkbox weird behavior (becomes disabled and clickable after bringing fragment from backsta
Android Checkbox weird behavior (becomes disabled and clickable after bringing fragment from backsta

Time:07-16

I am currently facing an issue using CheckBox in my fragment. Once the fragment is opened, the checkbox works properly. The check box's behavior changes in two case:

  • When I bring the fragment from the backStack using Back button
  • When I open the fragment for the second time.

I t seems like when the fragment is reCreated, the checkBox becomes gray (disabled) and still clickable.

<androidx.appcompat.widget.AppCompatCheckBox
            android:id="@ id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            app:layout_constraintTop_toBottomOf="@id/ivLogo"
            app:layout_constraintStart_toStartOf="@id/guideStart"
            app:layout_constraintEnd_toEndOf="@id/guideEnd"/>

I tried to save its state but didn't work.

PS: After getting this behavior, (checkbox.isEnabled = true) doesn't work anymore.

Any help ?

Thanks in advance.

CodePudding user response:

I believe you'd have to experiment with Android Activity Lifecycle. Seems like you would need to remember a state and then use it to set the checkbox to a correct, previous state using for example onResume() or something else.

CodePudding user response:

I found the solution !

I tried to override the theme of my Checkbox. The only one that worked for me is: Widget.MaterialComponents.CompoundButton.CheckBox

The solution was to use a custom theme as following:

<style name="ABCheckBox" parent="Widget.MaterialComponents.CompoundButton.CheckBox">
    <item name="android:textAppearance">?attr/textAppearanceBodyMedium</item>
    <item name="buttonTint">@null</item>
</style>

<androidx.appcompat.widget.AppCompatCheckBox
        android:id="@ id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:theme="@style/ABCheckBox"
        android:checked="true"
        android:enabled="true"
        android:minWidth="0dp"
        android:minHeight="0dp"
        android:button="@drawable/selector_checkbox"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

Hope it would help you guys !

  • Related