循环中的Kotlin ActivityMainBinding生成id



我有个问题。在我的xml文件中,我有多个具有以下id的textViews:

txtRow1Column1
txtRow1Column2
txtRow2Column1
txtRow2Column2
txtRow3Column1
txtRow3Column2
txtRow4Column1
txtRow4Column2

现在,我用1..2之间的随机数填充了一个数组,并使用1或2在资源的文本视图中添加文本。为此,我已经有了以下功能:

private fun startNewRound() {
// Define the array for (row, column, value)
val rows = arrayOf<Array<Int>>();
// Fill the array for each row and for each column
for (row in 1..4) {
rows.set(row, emptyArray())
for (column in 1..2) {
rows[row].plus((1..2).random())
}
}
// Show the correct text using the filled array
for (columns in rows) {
for (value in columns) {
val id = "txtRow" + rows.indexOf(columns) + "Column" + (columns.indexOf(value) + 1)
when (value) {
1 -> binding."ID HERE".text = getString(R.string.strTrue)
2 -> binding."ID HERE".text = getString(R.string.strFalse)
}
}
}
}

目前我添加了"ID HERE"而不是视图的id,因为我需要使用字符串作为id来绑定到视图。我的问题是:我如何使用该字符串来找到正确的id,并能够绑定到该特定视图?

附带说明,构建2D数组的方式看起来像O(n^2(,即使它不会抛出IndexOutOfBoundsException。

获取列索引的方式不起作用。假设您在一列中有两次值1。indexOf将两次都返回0,因为它返回第一个有效匹配。此外,在2D循环中使用indexOf会导致O(n^3(的复杂性,而它可能只是O(n(

对于您的问题,您可以使用Resources.getIdentifier()来查找视图的Int ID,这样您就可以使用findViewById来查找视图。另一种选择是在绑定类上使用反射来查找具有该名称的字段,但这更难看。

fun <T> View.getChildWithName(name: String): T {
val id = context.resources.getIdentifier("id", name, context.packageName)
return findViewById(id)
}
private fun startNewRound() {
val rows = Array(4) { Array(2) { (1..2).random() } }
rows.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, value ->
val id = "txtRow${rowIndex + 1}Column${colIndex  + 1}" 
val view = binding.root.getChildWithName<TextView>(id)
view.text = when (value) {
1 -> getString(R.string.strTrue)
2 -> getString(R.string.strFalse)
}
}
}
}

最新更新