My questions is relatively simple: How does the binding find the layout to my Main Actvity since I don't use the ID, I use the name "root". And how am I going to find different layouts to my other screens using the similar code?
MAIN ACTIVITY
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) // variable binding to access layout views
setContentView(binding.root) // here define o XML
}
}
I'm new to view binding. I haven't found a good resource to study it yet.
The ActivityMainBinding
is not named ActivityMainBinding
because you use it in the MainActivity
. It's generated based on a layout file that is named activity_main
so technically you are using specific ID but not via layout resource.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
is exactly the same as:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
without the utility of data binding ofc.
Once you have a layout that uses data binding structure, the binding is automatically generated. e.g. for layout activity_second
there will be ActivitySecondBinding
.