AndroidX 库包含架构组件,您可以使用它们设计健壮、可测试和可维护的应用。数据绑定库与架构组件无缝协作,进一步简化您的界面开发。应用中的布局可以绑定到架构组件中的数据,这有助于您管理界面控制器的生命周期,并通知界面数据中的更改。
此页面展示了如何将架构组件集成到您的应用中,以充分利用数据绑定库。
使用 LiveData 通知界面数据更改
您可以使用 LiveData
对象作为数据绑定源,自动通知界面数据中的更改。有关此架构组件的更多信息,请参阅 LiveData 概览。
与实现 Observable
的对象(例如可观察字段)不同,LiveData
对象了解订阅数据更改的观察者的生命周期。此知识带来了许多好处,具体请参阅使用 LiveData 的优势。在 Android Studio 3.1 及更高版本中,您可以在数据绑定代码中用 LiveData
对象替换可观察字段。
要将 LiveData
对象与您的绑定类一起使用,您需要指定一个生命周期所有者来定义 LiveData
对象的范围。以下示例在绑定类实例化后将 Activity 指定为生命周期所有者:
Kotlin
class ViewModelActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // Inflate view and obtain an instance of the binding class. val binding: UserBinding = DataBindingUtil.setContentView(this, R.layout.user) // Specify the current activity as the lifecycle owner. binding.setLifecycleOwner(this) } }
Java
class ViewModelActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Inflate view and obtain an instance of the binding class. UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user); // Specify the current activity as the lifecycle owner. binding.setLifecycleOwner(this); } }
您可以使用 ViewModel
组件(如下一节所述)将数据绑定到布局。在 ViewModel
组件中,您可以使用 LiveData
对象来转换数据或合并多个数据源。以下示例显示了如何在 ViewModel
中转换数据:
Kotlin
class ScheduleViewModel : ViewModel() { val userName: LiveDatainit { val result = Repository.userName userName = Transformations.map(result) { result -> result.value } } }
Java
class ScheduleViewModel extends ViewModel { LiveDatausername; public ScheduleViewModel() { String result = Repository.userName; userName = Transformations.map(result, result -> result.value); } }
使用 ViewModel 管理与界面相关的数据
数据绑定库与 ViewModel
组件无缝协作。ViewModel
公开布局观察并对其更改作出反应的数据。将 ViewModel
组件与数据绑定库结合使用,可以将界面逻辑从布局移出到组件中,这使得测试更容易。数据绑定库确保在需要时将视图与数据源绑定和解绑。其余大部分工作包括确保您公开正确的数据。有关此架构组件的更多信息,请参阅 ViewModel 概览。
要将 ViewModel
组件与数据绑定库结合使用,您必须实例化您的组件(它继承自 ViewModel
类),获取您的绑定类的实例,并将您的 ViewModel
组件分配给绑定类中的属性。以下示例显示了如何将该组件与库一起使用:
Kotlin
class ViewModelActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // Obtain the ViewModel component. val userModel: UserModel by viewModels() // Inflate view and obtain an instance of the binding class. val binding: UserBinding = DataBindingUtil.setContentView(this, R.layout.user) // Assign the component to a property in the binding class. binding.viewmodel = userModel } }
Java
class ViewModelActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Obtain the ViewModel component. UserModel userModel = new ViewModelProvider(this).get(UserModel.class); // Inflate view and obtain an instance of the binding class. UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user); // Assign the component to a property in the binding class. binding.viewmodel = userModel; } }
在您的布局中,使用绑定表达式将 ViewModel
组件的属性和方法分配给相应的视图,如以下示例所示:
<CheckBox
android:id="@+id/rememberMeCheckBox"
android:checked="@{viewmodel.rememberMe}"
android:onCheckedChanged="@{() -> viewmodel.rememberMeChanged()}" />
使用可观察 ViewModel 以更好地控制绑定适配器
您可以使用实现 Observable
接口的 ViewModel
组件,以通知其他应用组件数据中的更改,类似于您使用 LiveData
对象的方式。
在某些情况下,您可能更喜欢使用实现 Observable
接口的 ViewModel
组件,而不是使用 LiveData
对象,即使您失去了 LiveData
的生命周期管理功能。使用实现 Observable
的 ViewModel
组件可以更好地控制应用中的绑定适配器。例如,此模式让您可以更好地控制数据更改时的通知;它还允许您指定一个自定义方法来在双向数据绑定中设置属性的值。
要实现可观察的 ViewModel
组件,您必须创建一个继承自 ViewModel
类并实现 Observable
接口的类。当观察者订阅或取消订阅通知时,您可以使用 addOnPropertyChangedCallback()
和 removeOnPropertyChangedCallback()
方法提供自定义逻辑。您还可以在 notifyPropertyChanged()
方法中提供在属性更改时运行的自定义逻辑。以下代码示例显示了如何实现可观察的 ViewModel
:
Kotlin
/** * A ViewModel that is also an Observable, * to be used with the Data Binding Library. */ open class ObservableViewModel : ViewModel(), Observable { private val callbacks: PropertyChangeRegistry = PropertyChangeRegistry() override fun addOnPropertyChangedCallback( callback: Observable.OnPropertyChangedCallback) { callbacks.add(callback) } override fun removeOnPropertyChangedCallback( callback: Observable.OnPropertyChangedCallback) { callbacks.remove(callback) } /** * Notifies observers that all properties of this instance have changed. */ fun notifyChange() { callbacks.notifyCallbacks(this, 0, null) } /** * Notifies observers that a specific property has changed. The getter for the * property that changes must be marked with the @Bindable annotation to * generate a field in the BR class to be used as the fieldId parameter. * * @param fieldId The generated BR id for the Bindable field. */ fun notifyPropertyChanged(fieldId: Int) { callbacks.notifyCallbacks(this, fieldId, null) } }
Java
/** * A ViewModel that is also an Observable, * to be used with the Data Binding Library. */ class ObservableViewModel extends ViewModel implements Observable { private PropertyChangeRegistry callbacks = new PropertyChangeRegistry(); @Override protected void addOnPropertyChangedCallback( Observable.OnPropertyChangedCallback callback) { callbacks.add(callback); } @Override protected void removeOnPropertyChangedCallback( Observable.OnPropertyChangedCallback callback) { callbacks.remove(callback); } /** * Notifies observers that all properties of this instance have changed. */ void notifyChange() { callbacks.notifyCallbacks(this, 0, null); } /** * Notifies observers that a specific property has changed. The getter for the * property that changes must be marked with the @Bindable annotation to * generate a field in the BR class to be used as the fieldId parameter. * * @param fieldId The generated BR id for the Bindable field. */ void notifyPropertyChanged(int fieldId) { callbacks.notifyCallbacks(this, fieldId, null); } }
为您推荐
- 注意:当 JavaScript 关闭时,会显示链接文本
- 处理可观察数据对象
- 加载和显示分页数据
- 将 Kotlin 协程与生命周期感知型组件结合使用