android - 使用适配器模式实现 ChipGroup

标签 android adapter material-components-android android-chips

我的 fragment 包含一个ChipGroup,其中chips根据用户的选择动态添加。我希望实现的是一种适配器模式,其中 list 暴露给从中创建 chips 的适配器,用户可以在列表中添加/删除元素.

我找不到任何方法来做到这一点,现在,每当用户与列表交互时,所有筹码都会重新创建。

为了简洁起见,代码已被剪裁

XML 文件

// capturing the user's choice
      <RadioGroup
          android:id="@+id/vehicles_radio_group"
          android:onCheckedChanged="@{vehicleViewModel::radioCheckedChanged}">

View 模型

fun radioCheckedChanged(radioGroup: RadioGroup, checkedId: Int) {

        //validating the user's choice
            if (condition) {
                //code for adding the choice to a List
                vehicleDispatched(selectedVehicle, checkedId)   
            } else {
                selectionError()
            }
    }

    // adding the user's choice to the list
    // _dispatchingUnits is a LiveData

    private fun vehicleDispatched(selectedVehicle: DomainVehicle, checkedId: Int) {
  
     // appending the selected choice to the list(Type : List<Pair<Vehicle,Planet>>)
        _dispatchingUnits.value =
            _dispatchingUnits.value?.plus(selectedVehicle to _currentPlanet.value!!)
                ?: listOf(selectedVehicle to _currentPlanet.value!!)
    }

fragment

// register an observer and take action

        myViewModel.dispatchingUnits.observe(viewLifecycleOwner) { allPairs ->
            allPairs?.apply {

                with(binding) {
                   // remove the existing chips if any
                    if (selectedPairChipGroup.isNotEmpty()) {
                        selectedPairChipGroup.removeAllViews()
                    }
                  // create new chips
                    allPairs.forEach { chipPair ->
                        createChips(chipPair)
                    }
                }
            }
        }

期待类似的事情,

// In fragment class
val adapter = ChipAdapter()
binding.chipGroup.setAdapter(adapter)


// In bindingUtils file
@BindingAdapter("fill_data")
fun RecyclerChipGroup.setData(list : MyListType){
val adapter = this.adapter as ChipAdapter
adapter.submitChipList(list)
}

//XML File
<RecyclerChipGroup
....
app:fill_data = "@{viewModel.dispatchingUnits}"
....
/>

如何继续下去?

最佳答案

如果您想实现基于适配器的芯片列表以及比 ChipGroup 更多的控件,那么您可以使用 RecyclerView 将芯片作为一个项目,并按从左到右或从右到左的顺序排列芯片,您可以创建一个自定义布局管理器。

了解更多详情,您可以访问https://github.com/BelooS/ChipsLayoutManager 。该库提供对 ChipsLayoutManager 的支持。

关于android - 使用适配器模式实现 ChipGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65651888/

相关文章:

android - MaterialButton 和简单的 Button 有什么区别吗?

android - 使用带有复选框的android双向数据绑定(bind)

java - 设置 TextSpinner 适配器

android - 我们可以从适配器调用 startActivityForResult 吗?

android - BottomSheetDialogFragment View 仅在设备旋转后才变得透明

android - 如何在不重复的情况下更改 MaterialButton 的样式?

安卓工作室错误 : Execution failed for task ':app:processDebugManifest'

android - 阻止用户在退出应用程序后点击 'back'

android - 在android中录制视频时旋转图像帧

android - GridView Adapter.getView() 未正确设置选定状态