Kotlin:空对象引用上的getResources()

Ank*_*iya 1 arrays android android-context kotlin

我在kotlin中创建了这样的颜色数组

private var colorArray = arrayOf(
    ContextCompat.getColor(this, R.color.text_yellow),
    ContextCompat.getColor(this, R.color.text_green),
    ContextCompat.getColor(this, R.color.text_red)
)
Run Code Online (Sandbox Code Playgroud)

当我想通过索引从colorArray获取颜色时

var color = colorArray[0]
Run Code Online (Sandbox Code Playgroud)

我的索引0崩溃了,

尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'

我不知道我错在哪里如果我写ContextCompat.getColor(this,R.color.text_yellow)没问题,但是崩溃通过数组索引给了我错误

use*_*708 5

您将其声明为字段:

private var colorArray = arrayOf(
    ContextCompat.getColor(this, R.color.text_yellow),
    ContextCompat.getColor(this, R.color.text_green),
    ContextCompat.getColor(this, R.color.text_red)
)
Run Code Online (Sandbox Code Playgroud)

问题在于,在调用方法this之前,上下文(参数)为null onCreate()。并且,当您将某些内容声明为字段时,它将尝试在任何方法调用之前立即对其进行初始化。(因此在onCreate调用之前)

您可以做的是通过lazy呼叫初始化此字段。这意味着它实际上仅在首次使用时才被初始化。因此,如果您在AFTER之后调用索引onCreate,则上下文不会为空,并且应该可以正常工作。

更改为:

private var colorArray by lazy { arrayOf(
    ContextCompat.getColor(this, R.color.text_yellow),
    ContextCompat.getColor(this, R.color.text_green),
    ContextCompat.getColor(this, R.color.text_red)
) }
Run Code Online (Sandbox Code Playgroud)