【问题标题】:How can I shorten this code in Android using view binding by Kotlin?如何使用 Kotlin 的视图绑定在 Android 中缩短此代码?
【发布时间】:2021-12-24 23:06:37
【问题描述】:

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

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

【问题讨论】:

  • 您想要的是,每当按下按钮时,具有相同标签的网格应该将颜色更改为 R.color.btn_color,其他的更改为 R.color.btn_color_off。正确的?另外,kindGrid 是 recyclerView 还是什么?
  • 我不认为视图绑定会帮助你解决这个问题,因为它没有办法将视图分组到一个集合中。
  • @ArpitShukla kindGrid 是 GridLayout!是的!
  • @Tenfour04 是的.. 我想是的。

标签: android kotlin android-viewbinding


【解决方案1】:

您的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 -&gt; Button Map

【讨论】:

  • 这段代码真的很有帮助。我将不得不努力工作。 ??
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多