如何使用 Kotlin 的视图绑定在 Android 中缩短此代码?

How can I shorten this code in Android using view binding by Kotlin?


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        select(viewBinding.btnPearKind1)
        select(viewBinding.btnPearKind2)
        select(viewBinding.btnPearKind3)
        select(viewBinding.btnPearKind4)
        select(viewBinding.btnPearKind5)
        select(viewBinding.btnPearKind6)
    }

单击一个按钮会更改其他 5 个按钮。

我使用这些功能。

fun select(btn: Button){
        btn.setOnClickListener {      
            val kind = listOf("1","2","3","4","5","6")
            for(i in kind) {
                    if (i != btn.tag){
                        viewBinding.kindGrid.findViewWithTag<View>(i).backgroundTintList =
                            ContextCompat.getColorStateList(it.context, R.color.btn_color_off)
                    }else{
                        viewBinding.kindGrid.findViewWithTag<View>(i).backgroundTintList =
                            ContextCompat.getColorStateList(it.context, R.color.btn_color)
                    }
            }
        }
    }

我用视图组合写的时候,重复的代码是这样出来的。 我怎样才能减少它?

您的 select 函数已经被硬编码为通过外观查找视图层次结构中的所有按钮?就个人而言,我只是重新调整该代码的用途以创建按钮查找,然后您可以使用它来轻松设置点击侦听器和 UI 更改:

lateinit val buttons: List<Button>

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val tags = listOf("1","2","3","4","5","6")
    // look up all your buttons, creating a list of Button views
    buttons = tags.map { tag ->
        viewBinding.kindGrid.findViewWithTag<Button>(tag)
    }
    // now you can just apply a click listener to each of them
    buttons.forEach {
        setOnClickListener { view -> select(view as Button) }
    }
}

fun select(selected: Button){
    buttons.forEach { button ->
        // you could check the tags, but since we have a list of all the actual
        // buttons, we can just check which of them has been passed in
        val colour = if (button == selected) R.color.btn_color else R.color.btn_color_off
        button.backgroundTintList = ContextCompat.getColorStateList(it.context, colour)
    }
}

如果您需要通过标签直接查找按钮而不是迭代,您也可以使用 tags.associateWith 而不是 map 来构建 tag -> Button Map超过他们