Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Data Binding Binding Adapter with class reference

I created this Binding Adapter

@BindingAdapter("adapter")
public static void setAdapter(RecyclerView view, RecyclerView.Adapter<RecyclerView.ViewHolder> adapter)  {
    view.setAdapter(adapter);
}

and set in XML

app:adapter="@{com.package.Adapter}"

it gives all kinds of errors with it. What I want is to do the same thing as you can do with LayoutManager in XML like this

app:layoutManager="android.support.v7.widget.LinearLayoutManager"

Do you know how to solve this issue with passing a class?

P.S. I don't want to pass a variable reference in XML, because let's say I want to use only XML.

like image 566
Ihor Klimov Avatar asked Jul 10 '16 20:07

Ihor Klimov


1 Answers

It appears that you're trying to set a class in the XML, but are accepting an instance in your BindingAdapter. If you want to accept a class and instantiate it in your BindingAdapter, it will use reflection, like this:

@BindingAdapter("adapter")
public static void setAdapter(RecyclerView view, Class adapter)  {
    try {
        Object instance = adapter.newInstance();
        view.setAdapter((RecyclerView.Adapter)instance);
    } catch (Exception e) {
        Log.e(....);
    }
}

If you want to pass an instance to your binding (a better approach, IMO), you don't need a BindingAdapter. You can rely on the existing setAdapter call:

<layout>
    <data>
        <variable name="adapter" type="android.support.v7.widget.RecyclerView.Adapter"/>
    </data>
    <android.support.v7.widget.RecyclerView
        app:adapter="@{adapter}" .../>
</layout>
like image 186
George Mount Avatar answered Nov 15 '22 01:11

George Mount