AndroidX 程式庫包含架構元件,可用於設計功能完善、可測試且可維護的應用程式。資料繫結程式庫可與架構元件完美搭配運作,進一步簡化 UI 開發作業。應用程式中的版面配置可以繫結至架構元件中的資料,協助您管理 UI 控制器的生命週期,並通知 UI 資料變更。
本文說明如何將架構元件整合至應用程式,充分發揮資料繫結程式庫的效益。
使用 LiveData 通知 UI 資料變更
您可以使用 LiveData 物件做為資料繫結來源,自動向 UI 通知資料異動情形。如要進一步瞭解這個架構元件,請參閱「LiveData 總覽」。
與實作 Observable 的物件 (例如可觀測欄位) 不同,LiveData 物件知道訂閱資料變更的觀測器生命週期。這項知識可帶來許多好處,詳情請參閱「使用 LiveData 的優點」。在 Android Studio 3.1 以上版本中,您可以在資料繫結程式碼中,將可觀測欄位替換為 LiveData 物件。
如要將 LiveData 物件與繫結類別搭配使用,您必須指定生命週期擁有者來定義 LiveData 物件的範圍。以下範例在繫結類別例項化後,將活動指定為生命週期擁有者:
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: LiveData<String>
init {
val result = Repository.userName
userName = Transformations.map(result) { result -> result.value }
}
}
Java
class ScheduleViewModel extends ViewModel {
LiveData<String> username;
public ScheduleViewModel() {
String result = Repository.userName;
userName = Transformations.map(result, result -> result.value);
}
}
使用 ViewModel 管理 UI 相關資料
資料繫結程式庫可與 ViewModel 元件完美搭配。ViewModel 會公開版面配置觀察的資料,並對其變更做出反應。搭配使用 ViewModel 元件和 Data Binding Library,可將 UI 邏輯從版面配置移至元件,以便測試。資料繫結程式庫可確保檢視畫面在需要時與資料來源繫結及解除繫結。其餘工作大多是確保您公開正確的資料。如要進一步瞭解這個架構元件,請參閱「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()}" />
使用 Observable 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 協同程式