实现了具有适配器模式的芯片组



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

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

为了简洁起见,已对代码进行了剪裁

XML文件

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

ViewModel

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!!)
}

碎片

// 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将芯片作为一个项目,并按照从左到右或从右到左的顺序排列芯片,你可以创建一个自定义LayoutManager。

有关更多详细信息,您可以访问https://github.com/BelooS/ChipsLayoutManager.此库提供对芯片布局管理器的支持。

最新更新