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

Kotlin : getResources() on a null object reference

我已经在 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)
)

当我想从 colorArray 到 index

获取颜色时
var color = colorArray[0]

我在索引 0 上崩溃,

Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

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

您将其声明为字段:

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)
)

问题是在调用 onCreate() 方法之前,您的上下文(this 参数)为空。当您将某物声明为字段时,它会尝试在任何方法调用之前立即对其进行初始化。 (所以在调用 onCreate 之前)

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

改为:

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)
) }

您正在全局使用 this 作为 Context,但尚未初始化。 这就是您收到此错误的原因,因为 Context 为空。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()

执行此操作的正确方法是访问 onCreate() 中的上下文。您可以尝试以下操作:-

class Dx :AppCompatActivity(){
private lateinit var colorArray:Array<Int>
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_dx)
    colorArray = arrayOf(
            ContextCompat.getColor(this, R.color.colorAccent),
            ContextCompat.getColor(this, R.color.colorPrimary),
            ContextCompat.getColor(this, R.color.colorPrimaryDark)
    )
    val btn=findViewById<Button>(R.id.b1)
    btn.setBackgroundColor(colorArray[0])
}
}