简体   繁体   中英

Chip Group listener change chip position when fragment recreate

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM