如何使用Kotlin在Android Studio中制作EditText的2D排列列表



'''

class MainActivity : AppCompatActivity() {
private var button: Button? = null
private var textList: ArrayList<ArrayList<EditText>> = arrayListOf(arrayListOf())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById<Button>(R.id.solve)
textList[0][0]=findViewById<EditText>(R.id.ed1)
textList[0][1]=(findViewById(R.id.ed2))
textList[0][2]=(findViewById(R.id.ed3))
textList[0][3]=(findViewById(R.id.ed4))
textList[0][4]=(findViewById(R.id.ed5))
}
}

''

我想把EditText存储在2D数组列表中,但上面的方法不起作用。我不知道为什么,但当打开应用程序时,它会崩溃。那么我该怎么做呢?

这:

val list: ArrayList<Int> = arrayListOf()
list[0] = 123

是指";将索引0处的项替换为CCD_ 1";。但这是一个空列表,没有索引0。想象一下,您使用了索引2——如果可以在那里插入一些东西,那么索引1和0处会是什么?要想在列表中排名第三,就需要有第二项和第一项,对吧?

你可能想要一个数组:

private val rows = 5
private val columns = 5
private var textList: Array<Array<EditText>> = Array(rows) { arrayOfNulls(columns) }

这将为每一行创建一个数组,并用null填充,每列一个。然后你可以用findViewById(它可以返回null,这是你的ArrayList遇到的另一个问题——它只能容纳非null的EditText(

可能有更好的方法来做你正在做的事情,但这是你的基本问题——不能更新列表中不存在的项目。对于将要通过索引访问的固定结构,数组更有意义

最新更新