DataBinding - use base binding class

Viewed 685

Is it possible to somehow use DataBinding with inheritence? I want to define a custom interface and "bind" it to multiple layouts.

I know interfaces don't work with member variables but maybe someone knows a way (plugin) that creates member methods so that the binding creates those methods.

I want following:

public interface IIconBinding
{
    ImageView ivIcon();
}

And then I want to force may layouts to implement this interface and return the view with the id R.id.ivIcon in the interfaces functions. Code could look like following:

<layout
     xmlns:android="http://schemas.android.com/apk/res/android"
     app:interface="com.example.app.IIconBinding">

     <ImageView
        android:id="@+id/ivIcon"
        android:layout_width="36dp"
        android:layout_height="36dp" />

</layout>

Or similar. This example should just explain what I want to achieve. I want to be able to cast the binding that is created to an instance of IIconBinding and use this in the remaining code and I don't care if it is the layout above or ANY other layout that has on ImageView with the id ivIcon and implements the IIconBinding interface.

As far as I know this is not possible, but maybe someone knows an alternative way to achieve what I want?

Edit - Goal

The result should allow me to do following:

// all objects are DIFFERENT binding objects
Example1Binding binding1 = DataBindingUtil.bind(inflator.inflate(.R.layout.example1, container, false));
Example2Binding binding2 = DataBindingUtil.bind(inflator.inflate(.R.layout.example2, container, false));
Example3Binding binding3 = DataBindingUtil.bind(inflator.inflate(.R.layout.example3, container, false));

I KNOW that all 3 bindings contain an ImageView with the id ivIcon so I want to do following:

IIconBinding iconBinding1 = (IIconBinding) binding1;
IIconBinding iconBinding2 = (IIconBinding) binding2;
IIconBinding iconBinding3 = (IIconBinding) binding3;

And now I'm able to write a function that I can pass in an IIconBinding object and display an icon in the correct view, no matter if the binding is an object of Example1Binding, Example2Binding or Example3Binding, like following:

IconUtil.loadIcon(iconBinding1);
IconUtil.loadIcon(iconBinding2);
IconUtil.loadIcon(iconBinding3);

Without the common interface this would not work, I would need to wrap all bindings in a container or to write 3 different IconUtil.loadIcon(...) functions, one for each binding.

0 Answers
Related