首先,需要在build.gradle中添加databinding依赖:
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
implementation 'com.android.databinding:compiler:3.1.4'
}
然后,在fragment对应的布局文件中,使用layout标签来包裹布局,并设置data标签来指定数据源:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.example.myapp.viewmodel.MyViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
</layout>
接下来,在fragment中使用DataBindingUtil来获取绑定对象,并设置数据源:
class MyFragment : Fragment() {
private lateinit var binding: MyFragmentBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)
binding.viewModel = MyViewModel()
return binding.root
}
}
其中,MyViewModel为数据源对象。在布局中,可以通过@{}的方式来绑定数据:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.name}" />
其中,viewModel.name表示MyViewModel中的属性name。在数据源更新时,对应的UI元素也会自动更新。