Liên kết chế độ xem bố cục với thành phần kiến trúc

Thư viện AndroidX bao gồm Cấu trúc Các thành phần mà bạn có thể dùng để thiết kế các ứng dụng mạnh mẽ, có thể kiểm thử và bảo trì. Thư viện liên kết dữ liệu hoạt động liền mạch với Cấu trúc Các thành phần để đơn giản hoá hơn nữa phát triển giao diện người dùng. Bố cục trong ứng dụng của bạn có thể liên kết với dữ liệu trong Thành phần cấu trúc, giúp bạn quản lý vòng đời của trình điều khiển giao diện người dùng và thông báo cho giao diện người dùng về các thay đổi trong dữ liệu.

Trang này cho biết cách kết hợp các Thành phần cấu trúc vào ứng dụng để khai thác tối đa việc sử dụng Thư viện liên kết dữ liệu.

Sử dụng LiveData để thông báo cho giao diện người dùng về các thay đổi đối với dữ liệu

Bạn có thể sử dụng các đối tượng LiveData làm nguồn liên kết dữ liệu để tự động thông báo cho giao diện người dùng về những thay đổi trong . Để biết thêm thông tin về Thành phần cấu trúc này, hãy xem LiveData tổng quan.

Không giống như các đối tượng triển khai Observable – chẳng hạn như có thể quan sát trườngLiveData các đối tượng biết về vòng đời của đối tượng tiếp nhận dữ liệu đã đăng ký dữ liệu thay đổi. Kiến thức này mang lại nhiều lợi ích, như được giải thích trong lợi ích của việc sử dụng LiveData. Trong Android Studio phiên bản 3.1 trở lên, bạn có thể thay thế các trường có thể quan sát được với đối tượng LiveData trong mã liên kết dữ liệu.

Để sử dụng đối tượng LiveData với lớp liên kết, bạn cần chỉ định một chủ sở hữu vòng đời để xác định phạm vi của đối tượng LiveData. Nội dung sau đây ví dụ chỉ định hoạt động là chủ sở hữu vòng đời sau lớp liên kết đã được tạo thực thể:

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);
    }
}

Bạn có thể sử dụng ViewModel như được giải thích trong phần sau, để liên kết dữ liệu với bố cục. Trong thành phần ViewModel, bạn có thể sử dụng đối tượng LiveData để biến đổi dữ liệu hoặc hợp nhất nhiều dữ liệu nguồn. Ví dụ sau đây cho thấy cách chuyển đổi dữ liệu trong ViewModel:

Kotlin

class ScheduleViewModel : ViewModel() {
    val userName: LiveData

    init {
        val result = Repository.userName
        userName = Transformations.map(result) { result -> result.value }
    }
}

Java

class ScheduleViewModel extends ViewModel {
    LiveData username;

    public ScheduleViewModel() {
        String result = Repository.userName;
        userName = Transformations.map(result, result -> result.value);
    }
}

Sử dụng ViewModel để quản lý dữ liệu liên quan đến giao diện người dùng

Thư viện liên kết dữ liệu hoạt động liền mạch với Các thành phần ViewModel. ViewModel hiển thị dữ liệu mà bố cục quan sát được và phản ứng với các thay đổi của nó. Sử dụng Các thành phần ViewModel có Thư viện liên kết dữ liệu cho phép bạn di chuyển logic giao diện người dùng ra khỏi bố cục và đi vào các thành phần, dễ kiểm thử hơn. Dữ liệu Thư viện liên kết đảm bảo khung hiển thị được liên kết và không bị liên kết với dữ liệu nguồn khi cần. Hầu hết công việc còn lại là đảm bảo rằng bạn đang tiết lộ đúng dữ liệu. Để biết thêm thông tin về Cấu trúc này Thành phần, xem ViewModel tổng quan.

Để sử dụng thành phần ViewModel với Thư viện liên kết dữ liệu, bạn phải tạo thực thể cho thành phần – kế thừa từ ViewModel, hãy lấy một thực thể của lớp liên kết và chỉ định thành phần ViewModel cho một trong lớp liên kết. Ví dụ sau đây minh hoạ cách sử dụng thành phần có thư viện:

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;
    }
}

Trong bố cục, hãy chỉ định các thuộc tính và phương thức cho thành phần ViewModel vào các khung hiển thị tương ứng bằng cách sử dụng biểu thức liên kết, như minh hoạ sau ví dụ:

<CheckBox
    android:id="@+id/rememberMeCheckBox"
    android:checked="@{viewmodel.rememberMe}"
    android:onCheckedChanged="@{() -> viewmodel.rememberMeChanged()}" />

Sử dụng ViewModel có thể quan sát để kiểm soát tốt hơn các bộ chuyển đổi liên kết

Bạn có thể sử dụng ViewModel thành phần triển khai Giao diện Observable để thông báo cho người khác về các thay đổi trong dữ liệu, tương tự như cách bạn sẽ sử dụng Đối tượng LiveData.

Có những trường hợp mà bạn có thể muốn sử dụng Thành phần ViewModel triển khai Observable giao diện qua các đối tượng LiveData, ngay cả khi bạn mất vòng đời các chức năng quản lý của LiveData. Sử dụng thành phần ViewModel Việc triển khai Observable cung cấp cho bạn nhiều quyền kiểm soát hơn đối với các bộ chuyển đổi liên kết trong . Ví dụ: mẫu này giúp bạn có nhiều quyền kiểm soát hơn đối với các thông báo khi dữ liệu thay đổi; nó cũng cho phép bạn chỉ định một phương thức tuỳ chỉnh để đặt của một thuộc tính trong liên kết dữ liệu hai chiều.

Để triển khai một thành phần ViewModel có thể quan sát được, bạn phải tạo một lớp kế thừa từ lớp ViewModel và triển khai Observable . Bạn có thể cung cấp logic tuỳ chỉnh khi một trình quan sát đăng ký hoặc huỷ đăng ký nhận thông báo bằng addOnPropertyChangedCallback()removeOnPropertyChangedCallback() . Bạn cũng có thể cung cấp logic tuỳ chỉnh sẽ chạy khi thuộc tính thay đổi trong thời gian notifyPropertyChanged() . Ví dụ về mã sau đây biểu thị cách triển khai một đối tượng có thể quan sát 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);
    }
}

Tài nguyên khác

Để tìm hiểu thêm về liên kết dữ liệu, hãy tham khảo các tài nguyên khác.