我遇到一件事情,我需要在我的一个 Kotlin fragment 中循环 7 天。我知道如何在 Kotlin 中循环对象或变量。
var i=0
for(i<7){
// loop 7 objects in the activity create them and show it to the user
}
而且我已经有了一个要循环的对象。 var day = root.findViewById<LinearLayout>(R.id.day_1)
.我的问题是如何循环它以便用户可以看到所有七个循环对象。
有什么不明白的可以问我。
最佳答案
不可能(明智地)动态创建 ID。更好的方法是预先定义 ID 数组,然后循环遍历它。
val ids = arrayOf(R.id.day_1, R.id.day_2, R.id.day_3, R.id.day_4, R.id.day_5, R.id.day_6, R.id.day_7)
for (id in ids) {
val view = root.findViewById<LinearLayout>(id)
// view.visibility = View.VISIBLE
}
或者,如果您有对包含 View 的引用,您可以遍历它的 subview :
val layout = findViewById<LinearLayout>(R.id.myLayout)
for (i in 0 until layout.childCount) {
val view = layout.getChildAt(i)
// view.visibility = View.VISIBLE
}
关于android - 如何使用for循环在android kotlin中制作多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59514554/