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

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 コンポーネントをデータ バインディング ライブラリとともに使用すると、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()}" />

監視可能な ViewModel を使用して、バインディング アダプターを詳細に管理する

Observable インターフェースを実装する ViewModel コンポーネントを使用すると、LiveData オブジェクトを使用する場合と同様に、データの変更を他のアプリ コンポーネントに通知できます。

LiveData のライフサイクル管理機能が失われるとしても、LiveData オブジェクトを使用するよりも、Observable インターフェースを実装する ViewModel コンポーネントを使用する方が望ましい場合があります。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);
    }
}

参考情報

データ バインディングについて詳しくは、以下の参考情報をご覧ください。