レイアウト ビューをアーキテクチャ コンポーネントにバインドする

AndroidX ライブラリには、Architecture コンポーネント。これらのコンポーネントを 堅牢でテストと保守が容易なアプリを設計するために使用できます。 データ バインディング ライブラリはアーキテクチャとシームレスに連携する ワークフローのさらなる簡素化を UI の開発に集中できますアプリのレイアウト アーキテクチャ コンポーネント内のデータとバインドできるため、 UI コントローラのライフサイクルを管理し、データの変更を UI に通知します。

このページでは、アーキテクチャ コンポーネントをアプリに組み込む方法について説明します。 データ バインディング ライブラリを最大限に活用できるよう、

LiveData を使用してデータの変更について UI に通知する

LiveData オブジェクトは、 変更について UI に自動的に通知するように、データ バインディング ソースを 分析できますこのアーキテクチャ コンポーネントについて詳しくは、LiveData のドキュメントをご覧ください。 概要をご覧ください。

実装するオブジェクトとは異なり、 Observable - 例: 観察可能 フィールド - LiveData オブジェクトは、データに登録しているオブザーバーのライフサイクルを認識します。 できます。こうした知識は多くのメリットをもたらします。詳細は、 Google Cloud Managed Service for Prometheus 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

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

ViewModel を使用して UI 関連のデータを管理する

データ バインディング ライブラリは、 ViewModel コンポーネント。ViewModel レイアウトが監視するデータを公開し、その変更に対応します。使用 Data Binding ライブラリの ViewModel コンポーネントを使用すると、UI ロジックを移動できます レイアウトからコンポーネントに移動できるため、テストが簡単です。データ バインディング ライブラリにより、ビューがデータからバインド、バインド解除されることを確実にする できます。残りの作業のほとんどは、インフラストラクチャの 正しいデータを公開できますこのアーキテクチャについて詳しくは コンポーネントについては、ViewModel で 概要をご覧ください。

データ バインディング ライブラリで ViewModel コンポーネントを使用するには、次のことを行う必要があります。 コンポーネントをインスタンス化します。このコンポーネントは ViewModel クラスを使用して、 バインディング クラスのインスタンスを作成し、ViewModel コンポーネントを プロパティを宣言します。次の例は、BigQuery の 次のライブラリを使用します。

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 を使用して、バインディング アダプターを詳細に管理する

ViewModel を使用できます。 コンポーネントを 1 つ実装します。 Observable インターフェース 通知する アプリケーション コンポーネントに、データの変更を通知します。これは、 LiveData オブジェクト。

状況によっては、kubectl の Observable を実装する ViewModel コンポーネント ライフサイクルが失われても LiveData オブジェクトの使用に対するインターフェース LiveData の管理機能。ViewModel コンポーネントを使用して、 Observable を実装することで、 。たとえば、このパターンでは通知をきめ細かく制御できます。 データの変更時また、カスタム メソッドを指定して、 双方向データ バインディングの属性の値。

監視可能な 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);
    }
}

参考情報

データ バインディングについて詳しくは、以下をご覧ください。 追加リソースをご覧ください