You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何用with处理多对象?多View统一设尺寸如何精简代码?

精简方案

你可以把需要调整尺寸的View整合到集合中,通过遍历统一设置参数,彻底消除重复代码:

private fun changeSize() {
    // 重命名变量避免和View自身的height/width属性冲突
    val targetHeight = height
    val targetWidth = width
    
    listOf(binding.leftBotIv, binding.leftTopIv, binding.rightBotIv, binding.rightTopIv)
        .forEach { view ->
            view.layoutParams.apply {
                height = targetHeight
                width = targetWidth
            }
        }
}

关键优化点

  • 用listOf将多个View打包成集合,通过forEach批量处理
  • 借助apply函数直接在layoutParams对象内部修改属性,代码更紧凑
  • 原代码中变量名height/width容易和View自身的同名属性混淆,重命名为targetHeight/targetWidth提升可读性

内容的提问来源于stack exchange,提问作者dobriy denyok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:20:55