nashcft's blog

時々何か書く。

Android: Data Binding 3.6.0 から ViewDataBinding の定義が変わった

今日 Android Studio 3.6.0 stable がリリースされた。

android-developers.googleblog.com

3.6 から導入された機能の一つに view binding という、data binding の layout 中の要素にアクセスする機能だけを抜き出したようなものがある。

developer.android.com

機能の詳細については公式ドキュメントを見てもらうとして、この機能で data binding の時のように生成される Binding クラスは ViewBinding という interface を実装している。

/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package androidx.viewbinding;

import android.view.View;
import androidx.annotation.NonNull;

/** A type which binds the views in a layout XML to fields. */
public interface ViewBinding {
    /**
     * Returns the outermost {@link View} in the associated layout file. If this binding is for a
     * {@code <merge>} layout, this will return the first view inside of the merge tag.
     */
    @NonNull
    View getRoot();
}

(from: AndroidX Tech: Source Code for ViewBinding.java)

この ViewBinding だが、3.6.0 から data binding で生成される Binding クラスの親クラスである ViewDataBinding もこれを実装するようになっている。

3.5 まで (3.5.3): AndroidX Tech: Source Code for ViewDataBinding.java

public abstract class ViewDataBinding extends BaseObservable

3.6 から (3.6.0): AndroidX Tech: Source Code for ViewDataBinding.java

public abstract class ViewDataBinding extends BaseObservable implements ViewBinding

つまり、 ViewBindingViewDataBinding, それと data binding や view binding で生成された Binding クラスの関係は以下のようになる。

ViewBinding
 |
 + - < View binding の機能で生成された Binding クラス >
 |
 + - ViewDataBinding
        |
        + - < Data binding の機能で生成された Binding クラス >

それが何か、というと、 <T extends ViewBinding> (Kotlin だと <T: ViewBinding>) みたいな型パラメータを定義すると view binding で生成されたクラスだけではなく data binding で生成されたクラスも適用可能になるということで、view binding と data binding は1つのプロジェクトに混在させることができるので、ViewBinding に関する実装を書いた時はそれに data binding の生成クラスを放り込んでも問題ないか考慮しておいた方が良いよ、という話。

追記