目錄
Steps to use data binding to replace calls to findViewById()
Steps for binding views to data
Steps to use data binding to replace calls to findViewById()
1. Enable data binding in the android{} of the build.gradle (Module: app) file
dataBinding {
enabled = true
}
2. Use <layout> as the root view in XML layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- 各種Layout放在中間 -->
</layout>
3. Define a binding variable (maybe before the onCreate())
private lateinit var binding: ActivityMainBinding
4. Create a binding object, replacing setContentView (obviously in the onCreate())
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
5. Replace findViewById() with references to the view in the binding object
binding.doneButton
// the name of the view is generated camel case from the view's id in the XML
6. Kotlinize(simplifiy) the function by using binding.apply{}
binding.nicknameText.text = binding.nicknameEdit.text
binding.nicknameEdit.visibility = View.GONE
binding.doneButton.visibility = View.GONE
binding.nicknameText.visibility = View.VISIBLE
binding.apply {
nicknameText.text = nicknameEdit.text.toString()
nicknameEdit.visibility = View.GONE
doneButton.visibility = View.GONE
nicknameText.visibility = View.VISIBLE
}
Steps for binding views to data
1. Create a data class for your data (maybe defined in a extra kotlin file)
data class MyName(var name: String = "", var nickname: String = "")
2. Add a <data> block inside the <layout> tag
3. Define a <variable> with a name and a type that is the data class
<data>
<variable
name="myName"
type="com.example.android.aboutme.MyName" />
</data>
4. Now you can use dot notation to access the data inside the data class.
android:text="@={myName.name}"
5. In MainActivity, create a variable with an instance of the data class (maybe before the onCreate())
private val myName: MyName = MyName("Aleks Haecky")
6. In the binding object, set the variable to the variable you just created (maybe in the onCreate())
binding.myName = myName
Why use Data Binding
Every time you use findViewById() to search for a view after the view is created or recreated, the Android system traverses the view hierarchy at runtime to find it.
When your app has only a handful of views, this is not a problem. However, production apps may have dozens of views in a layout, and even with the best design, there will be nested views.
One solution is to create an object that contains a reference to each view. This object, called a Binding object, can be used by your whole app. This technique is called data binding.
Once a binding object has been created for your app, you can access the views, and other data, through the binding object, without having to traverse the view hierarchy or search for the data.