创建按钮ArrayList Kotlin并选择框

时间:2018-07-22 10:30:00

标签: android arrays android-studio arraylist kotlin

我正在制作井字游戏。随着玩家获胜,获胜的盒子应该获得不同的颜色。为此,我赢得了[1,2,3][4,5,6]阵列中的盒子号码。 我在activity_main.xml中的框名为box1,box2,box3...box9。 我想借助[1,2,3]等动态选择框。 我创建了如下数组列表,但此代码应用未打开。 如何创建按钮arraylist,或者有什么方法可以借助数组-[1,2,3]

动态更改3种框的颜色
    var boxes:ArrayList<Button> = arrayListOf(
        findViewById(R.id.box1),
        findViewById(R.id.box2),
        findViewById(R.id.box3),
        findViewById(R.id.box4),
        findViewById(R.id.box5),
        findViewById(R.id.box6),
        findViewById(R.id.box7),
        findViewById(R.id.box8),
        findViewById(R.id.box9)
)

2 个答案:

答案 0 :(得分:0)

在您的活动中声明此列表:

var boxes: ArrayList<Button> = arrayListOf()

并在onCreate中添加:

    boxes = arrayListOf(
        findViewById(R.id.box1),
        findViewById(R.id.box2),
        findViewById(R.id.box3),
        findViewById(R.id.box4),
        findViewById(R.id.box5),
        findViewById(R.id.box6),
        findViewById(R.id.box7),
        findViewById(R.id.box8),
        findViewById(R.id.box9)
    )

答案 1 :(得分:-1)

您是否尝试过使其lazy?当前,您正在尝试在创建视图之前查找它们。

val boxes by lazy { 
    listOf(
        findViewById(R.id.box1),
        findViewById(R.id.box2),
        findViewById(R.id.box3),
        findViewById(R.id.box4),
        findViewById(R.id.box5),
        findViewById(R.id.box6),
        findViewById(R.id.box7),
        findViewById(R.id.box8),
        findViewById(R.id.box9)
    )
}