why doesn't layoutInflater work in class level in android from kotlin?

Viewed 45

I discover something strange in android studio while write a code. that is layoutInflater doesn't work in class out of method. if i write a the following code and run it, app doesn't work. why does this phenomenon happen?

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    val li = layoutInflater
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
1 Answers
val li = layoutInflater

This is equivalent to:

val li = getLayoutInflater()

In general, do not call methods on Activity or superclasses — such as getLayoutInflater() — until after you call super.onCreate(). Usually, those methods will not work, because the activity has not been initialized yet.

Related