简体   繁体   中英

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?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM