如何以编程方式选择 Android 中 ChipGroup 中的默认芯片?

Lor*_*oli 2 android android-layout material-design android-chips

TL;DR - 以编程方式选择作为 Android 中 ChipGroup 子代的默认选择芯片的正确方法是什么?

——

在我的 android 应用程序中,我使用com.google.android.material.chip.Chip样式作为@style/Widget.MaterialComponents.Chip.Choice组件来表示用户可以为给定路线选择的活动选择(想想步行、自行车等)

因为一条路线可以有不同类型的活动,所以我以编程方式将每种类型作为不同的芯片插入到com.google.android.material.chip.ChipGroup. 我还在片段的 onViewCreated() 期间使用以下代码选择默认芯片作为插入列表中的第一个芯片

 private fun setupTypeSelection(types: List<Type>) {
    types.forEach { type ->
        val chip = layoutInflater.inflate(R.layout.chip_type, viewBinding.typeChipGroup, false) as Chip

        chip.tag = type
        /* Init chip text and icon */

        chip.setOnClickListener {
            /* Update selected type */
        }

        if (currentType == null) {
            chip.isSelected = true
            currentType = type
        }

        viewBinding.typeChipGroup.addView(chip)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 ChipGroup 的布局定义,其中我设置了单选等

chip_group_layout.xml

<com.google.android.material.chip.ChipGroup
      android:id="@+id/type_container"

      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="@dimen/margin_medium"

      app:chipSpacingHorizontal="@dimen/margin_medium"
      app:selectionRequired="true"
      app:singleLine="true"
      app:singleSelection="true" />
Run Code Online (Sandbox Code Playgroud)

这是芯片布局

芯片类型.xml

<com.google.android.material.chip.Chip 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"

     style="@style/Widget.MaterialComponents.Chip.Choice"

     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

     app:chipIconEnabled="true" />
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,chip.isSelected = true即使在用户通过 UI 交互选择不同的芯片后,以编程方式设置为选定的芯片仍处于选中状态。

以编程方式选择作为 Android 中 ChipGroup 子代的默认选择 Chip 的正确方法是什么?

Lor*_*oli 6

找到了我的答案。

  • 使用View.generateViewId()新的 Id 并将其分配给新创建的芯片。然后加
  • 将芯片添加到其父芯片组
  • 检查芯片视图 ChipGroup 使用 viewBinding.typeChipGroup.check(id)

这是最终的代码:

private fun setupTypeSelection(types: List<Trail.Type>) {

    types.forEach { type ->
        val chip = layoutInflater.inflate(R.layout.chip_trail_type, viewBinding.typeContainer, false) as Chip

        chip.id = View.generateViewId()
        /* Set chip details as usual */

        viewBinding.typeContainer.addView(chip)

        if (currentType == null) viewBinding.typeChipGroup.check(chip.id)
    }
}
Run Code Online (Sandbox Code Playgroud)