What is “DataBindingComponent” class in android databinding?

后端 未结 2 889
感动是毒
感动是毒 2021-01-31 04:43

I have seen the DataBindingComponent in the official API doc.

https://developer.android.com/reference/android/databinding/DataBindingUtil.html

Th

2条回答
  •  轮回少年
    2021-01-31 05:36

    From the documentation we know

    This interface is generated during compilation to contain getters for all used instance BindingAdapters. When a BindingAdapter is an instance method, an instance of the class implementing the method must be instantiated. This interface will be generated with a getter for each class with the name get* where * is simple class name of the declaring BindingAdapter class/interface. Name collisions will be resolved by adding a numeric suffix to the getter.

    An instance of this class may also be passed into static or instance BindingAdapters as the first parameter.

    If using Dagger 2, the developer should extend this interface and annotate the extended interface as a Component.

    This tells us this interface is used and generated for injecting a factory for instances implementing custom @BindingAdapter methods. Like this you can configure the data bindings for different situations or layouts or supply it with a more general state. If you have a look at the default DataBindingComponent class in Android Studio you find it located in build/generated/source/apt/dev.

    The methods you can use with the DataBindingComponent are

    • DataBindingUtil.setDefaultComponent()
    • DataBindingUtil.inflate()
    • DataBindingUtil.bind()

    Considering you define an interface like

    public interface Foo {
        @BindingAdapter("foobar")
        void fooBar(View view, String baz);
    }
    

    an android.databinding.DataBindingComponent interface gets generated

    public interface DataBindingComponent {
        di.pkg.Foo getFoo();
    }
    

    This @BindingAdapter host now gets used in your data bindings, but you need to implement the interface yourself and use it with one of the methods given above like

    DataBindingUtil.setDefaultComponent(new DataBindingComponent(){
        @Override
        public Foo getFoo() {
            return new Foo() {
                @Override
                public void fooBar(View view, String baz) {
                    if (view instanceof TextView) ((TextView) view).setText(baz);
                }
            };
        }
    });
    

    In your example you get null from DataBindingUtil.getDefaultComponent() because you've never set the default component yourself.

提交回复
热议问题