Reputation: 2258
I'm creating a chip programmatically. The chips are created but when the app stops (not destroyed) and re-opens, the position of the chip changes in the chip Group Listener.
Here is my code:
private lateinit var playlist: Array<Pair<String, String>>
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
for (item in playlist){
createChip(item.first)
}}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
chip_group.setOnCheckedChangeListener { chipGroup, position ->
for (i in 0 until chipGroup.childCount){
val chip = chipGroup.getChildAt(i)
chip.isClickable = chip.id != chipGroup.checkedChipId
}
Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show()
}}
fun createChip(name: String){
val chip = Chip(chip_group.context)
chip.text = name
chip.isClickable = true
chip.isCheckable = true
chip.isCheckedIconVisible = false
chip_group.addView(chip)
}
I'm expecting the chip to have the same position when the app re-opens, but instead the position increases.
Upvotes: 0
Views: 3118
Reputation:
You are mixing id
with position
.
onCheckedChanged(ChipGroup group, int checkedId)
is interface method called when the checked chip has changed.
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
var index=0
for (item in playlist){
createChip(item.first,index++)
}}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
chip_group.setOnCheckedChangeListener { chipGroup, id ->
for (i in 0 until chipGroup.childCount){
val chip = chipGroup.getChildAt(i)
chip.isClickable = chip.id != chipGroup.checkedChipId
}
Toast.makeText(context, position.toString(), Toast.LENGTH_SHORT).show()
}}
fun createChip(name: String,index:Int){
val chip = Chip(chip_group.context)
chip.text = name
chip.isClickable = true
chip.isCheckable = true
chip.isCheckedIconVisible = false
chip.id=index //maybe you can use tag
chip_group.addView(chip)
}
Upvotes: 1