重新创建片段时,芯片组侦听器更改芯片位置

时间:2019-01-20 06:28:18

标签: android kotlin fragment android-chips

我正在以编程方式创建芯片。芯片已创建,但是当应用停止(未销毁)并重新打开时,芯片的位置在芯片组侦听器中发生了变化。

这是我的代码:

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

我希望重新打开应用程序时,芯片的位置相同,但位置会增加。

1 个答案:

答案 0 :(得分:1)

您正在将idposition混合。
onCheckedChanged(ChipGroup group, int checkedId)是已检查的芯片已更改时调用的接口方法。

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