我正在接近Kotlin(和移动编码) 我正在try 将一个监听器设置为在单击多个文本视图的每个人时运行相同的函数. 我在so上找到了下面的代码(对不起,缺少链接:我又找不到了) 但是,当我试图将extView传递给该函数时,最后一个"it"出现错误.

    val txtV_Ans1 = findViewById(R.id.txtV_Aswer1) as TextView
    val txtV_Ans2 = findViewById(R.id.txtV_Aswer2) as TextView
    val txtV_Ans3 = findViewById(R.id.txtV_Aswer3) as TextView
    val txtV_Ans4 = findViewById(R.id.txtV_Aswer4) as TextView

    val txtVs_Ans = arrayListOf(
        txtV_Ans1,
        txtV_Ans2,
        txtV_Ans3,
        txtV_Ans4
    )
    txtVs_Ans.forEach { it.setOnClickListener { txtV_Fill(it, "You clicked here")} }

fun txtV_Fill(txtV: TextView, txtToInsert: String){
    txtV.text = txtToInsert
}

推荐答案

您提供的代码似乎基本正确,但您遇到了一个问题,因为forEach lambda中的it引用在此上下文中没有引用TextView.您应该使用更显式的方法将TextView传递给txtV_Fill函数.

val txtV_Ans1 = findViewById(R.id.txtV_Aswer1) as TextView
val txtV_Ans2 = findViewById(R.id.txtV_Aswer2) as TextView
val txtV_Ans3 = findViewById(R.id.txtV_Aswer3) as TextView
val txtV_Ans4 = findViewById(R.id.txtV_Aswer4) as TextView

val txtVs_Ans = arrayListOf(
    txtV_Ans1,
    txtV_Ans2,
    txtV_Ans3,
    txtV_Ans4
)

txtVs_Ans.forEach { txtView ->
    txtView.setOnClickListener { 
        txtV_Fill(txtView, "You clicked here")
    }
}

fun txtV_Fill(txtV: TextView, txtToInsert: String) {
    txtV.text = txtToInsert
}

Android相关问答推荐

将Android Studio插件复制到离线网络

滚动屏幕时更改按钮外观

无法从API访问项目详细信息

如何在Android Studio中将我的Java-库&库设置为Kotlin库

Android Studio中的Kotlin版本不兼容错误:需要元数据1.9.0,但找到1.6.0

在柯特林连续测量网速

为什么可以';我不能直接在RecyclerView.ViewHolder中访问视图ID吗?

AndroidX Media3 迁移指南

Android v31 及更低版本中 ImageView 中的圆角

如何用jetpack compose实现垂直李克特量表

如何在 React Native 中调试网络响应

如何在 Jetpack Compose 中向图像视图添加对角色带?

Jetpack Compose 惰性列在单个项目更新时重新组合所有项目

如何在 Jetpack Compose 中的 VisualTransformation 之后将光标保持在文本字段的末尾

Jetpack Compose 重组竞争条件

Jetpack Compose Alignment - 误解了 alignBy 修饰符

将房间中的实体更新为 isCompleted 并使用 Flow 问题获取所有数据

如何对齐文本和图标可组合,以便即使在文本溢出后它们也能保持在一起?

如何删除 Ktor 客户端 2.0.0 的默认标头

如何使在库范围之外无法访问的接口的具体实现.?