Issue
I'm new to Android development. When I use ViewBinding to access items in the layout, I encountered a problem about where to initialize variable.
As you can see in the code, I declare two instance variables, but only initialize the variable tag before onCreate method.
My question is that why can't I initialize variable binding like variable tag before onCreate method since I can access to variable tag in the onCreate method without error? I did a test that initialize binding before onCreate but the program crashed.
Here is my code:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val tag = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(tag, "onCreate") // I can access to variable tag
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.startNormalActivity.setOnClickListener {
val intent = Intent(this, NormalActivity::class.java)
startActivity(intent)
}
binding.startDialogActivity.setOnClickListener {
val intent = Intent(this, DialogActivity::class.java)
startActivity(intent)
}
}
}
Solution
To inflate a layout either directly or via a binding, you need a LayoutInflater
. System services such as layout inflaters are not available to an Activity
before its onCreate
lifecycle phase. Instance initialization is too early.
Your tag
is initialized with a string literal and that is certainly possible at init phase.
Answered By - laalto
Answer Checked By - Cary Denson (JavaFixing Admin)