Checked ID more than Child Count in ChipGroup Android when clicked right away

162 views Asked by At

I created a Chip dynamically based on a list, and set OnCheckedChangeListener to the ChipGroup. So supposed there is 2 items in the list, the possible checkedId should be 1 or 2. But i find weird behavior when i clicked the filter right away on the first item (like in less than 1 second after the screen opened), the checkedId is 3. But if i wait a bit, like after 1 second, the checkedId will be 1. Why is this happened? And what is the good way to solve it?

enter image description here

Code to Add Chip

fun ChipGroup.addChip(context: Context, label: String) {
    val chip = context.layoutInflater.inflate(R.layout.layout_chip, this, false) as Chip
    chip.text = label
    addView(chip)
}

Chipgroup code:

setOnCheckedChangeListener { _, checkedId ->
    debug { "CheckedId: childCount - $childCount" }
    debug { "CheckedId: checkedId - $checkedId" }
    debug { "CheckedId: checkedIds - $checkedChipIds" }
    val selectedCategory = if (checkedId != View.NO_ID) {
        result.data[checkedId - 1]
    } else null
}

ChipGroup XML

<com.google.android.material.chip.ChipGroup
                android:id="@+id/chipGroupCategories"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:singleSelection="true" />

layout_to_be_inflated XML

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.chip.Chip xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkable="true"
    android:textAppearance="@style/MyText.SemiBold"
    android:textColor="@color/selector_text_chip_category"
    app:checkedIconEnabled="false"
    app:chipBackgroundColor="@color/selector_background_chip_category"
    app:chipCornerRadius="8dp"
    tools:text="Food" />
0

There are 0 answers