【问题标题】:How to get all ImageButton ID's on Android with Kotlin如何使用 Kotlin 在 Android 上获取所有 ImageButton ID
【发布时间】:2022-12-06 07:03:34
【问题描述】:

我有ImageButtons 我从override fun onCreate(savedInstanceState: Bundle?) 发来祝酒词 当它点击成功时。

我想遍历所有 ImageButtons 以将 setOnClickListener 添加到它们。

这有效:

没有循环工作:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<ImageButton>(R.id.r1col1).setOnClickListener {
            toastContentDescription(it)
        }
    }
    private fun toastContentDescription(it: View) {
        val contentDescription = it.contentDescription
        val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
        myToast.show()
    }
}

不工作,不再开始

我在这里找到了一个 Android Java 按钮的例子:How to get all Buttons ID's in one time on Android

所以我修改了我的代码如下。但随后该应用程序不再启动(没有给我任何错误)。

我想我必须先获得 id,然后问题才能解决。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        for (i in 0..4) {
            val id: Int = resources.getIdentifier("R.id.r1col$i", "id", this.packageName)
            findViewById<ImageButton>(id).setOnClickListener {
                toastContentDescription(it)
            }
        }
    }
    private fun toastContentDescription(it: View) {
        val contentDescription = it.contentDescription
        val myToast = Toast.makeText(applicationContext, contentDescription, Toast.LENGTH_SHORT)
        myToast.show()
    }
}

有什么方法可以将 setOnClickListener 设置为循环(等)代码中的所有 ImageButtons?

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    从您传递的字符串中删除 "R.id." 前缀。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多