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)
}
}
}
CodePudding user response:
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.
CodePudding user response:
You cannot create binding before OnCreate() .Bindings are auto-generated classes which are responsible so that the view hierarchy isn't modified before it binds to the views with expressions within the layout. OnCreate() is the first function which is called when a Activity is created . Refer here for more details to know about Activity LifeCycle :
https://developer.android.com/guide/components/activities/activity-lifecycle
So when an Activity is created you inflate the layout that you created in the form of xml file. After inflating the layout the binding process is instantiated. The process of inflating the layout is carried out in OnCreate(), as you can see in your code :
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
Thus, you cannot generate bindings before OnCreate() and has to be done in OnCreate or post anytime after inflating your layout.