Kotlin数组的按钮都是空的

问题描述 投票:0回答:1

创建一个按钮阵列

    val buttons = arrayOf(spot0, spot1, spot2, spot3, spot4, spot5, spot6)
    Log.v("array", "spot0=" + buttons[0])

    images.shuffle()
    val randomnumber = (0..5).random()

    buttons[0].setBackgroundResource(images[randomnumber])

得到这个错误信息。

java.lang.NullPointerException: 试图在一个空对象引用上调用虚拟方法'void android.widget.ImageButton.setBackgroundResource(int)'。

和这个日志输出。

Varray: spot0=null

这是Kotlin,所以据我所知,我不应该调用findViewById。

应用插件。'kotlin-android-extensions'被添加到我的build.gradle中。

按钮是在xml中设置的。

<ImageButton
    android:id="@+id/spot0"
    android:text="zero"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="131dp"
    android:layout_marginLeft="131dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="131dp"
    android:layout_marginRight="131dp"
    android:background="@drawable/heart"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.565"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我试图随机化我的按钮图像 并试图通过一个数组来实现。我如何才能做到这一点?

android arrays kotlin nullpointerexception
1个回答
1
投票

如果你是在 Activity:

你应该打电话给我 setContentView(R.id.your_layout) 方法,在Activity的 onCreate() 方法,然后再访问视图和初始化数组。

如果你是在 Fragment:

试着访问视图并初始化数组。onViewCreated() 方法。

© www.soinside.com 2019 - 2024. All rights reserved.