Step 1: Enable data binding
Open the build.gradle (Module: app)
file.
Inside the android
section, before the closing brace, add a buildFeatures
section and set dataBinding
to true
.
buildFeatures {
dataBinding true
}
Because of kotlin , you should use the kotlin-kapt
plugin to avoid the warning in AS.
//also in build.gradle (Module: app) file
plugins {
id 'kotlin-kapt'
}
Step 2: Change layout file to be usable with data binding
To work with data binding, you need to wrap your XML layout with a <layout>
tag.
Open the activity_main.xml
file.
Add <layout></layout>
as the outermost tag around the <LinearLayout>
.
<layout>
<LinearLayout ... >
...
</LinearLayout>
</layout>
tips: use the Alt+Enter
in the LinearLayout
tag to quickly generate the <layout >
wrap
How to Use data-binding in Activity/Fragment
- first method
private lateinit var binding: ActivityMainBinding
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
in fragment with the databinding:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentTitleBinding>(inflater,
R.layout.fragment_title,container,false)
return binding.root
}
- Second method(easier)
val binding = FragmentTitleBinding.inflate(inflater)