My fragment contains a ChipGroup
with the chips
being added dynamically based on the users choice. What I wish to accomplish is an adapter pattern where a list
is exposed to the adapter from which chips
are being created user gets to add/remove the elements to and from the list.
I couldn't find any way to do that and right now, whenever the user interacts with the list, all the chips are recreated.
Code has been clipped for the sake of brevity
XML file
// 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!!)
}
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)
}
}
}
}
Expecting something like,
// 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}"
....
/>
how to go on with it?
question from:
https://stackoverflow.com/questions/65651888/implementing-a-chipgroup-with-adapter-pattern 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…