Generate data-view-binding adapters of android recycler view.

Related tags

Adapter android
Overview

Items

Build Status codecov

这个库可以为 Android 的 RecyclerView 生成基于 Data-View-Binding 的 Adapter。

对比其他一些类似的开源库,它有以下的一些优势:

  • 更好的拓展性。这个库不需要你继承特定的 Adapter 或 ViewHolder 类,你可以继承任何第三方提供的基类;
  • 更好的性能。使用 Annotation Processor 意味着实现 Binding 时无需使用反射。支持 增量处理
  • 更低的侵入性。和传统的 Adapter 写法类似,可以快速从旧的 Codebase 迁移到新的写法;
  • 更可靠的代码。提供了单元测试覆盖大部分的 Case。

集入

替换以下代码中的 ${lastest-version} 为最新版本号 ,并复制到 Android 工程中的 build.gradle 脚本:

repositories {
    maven { url "https://jitpack.io" }
}
dependencies {
    implementation "com.github.nekocode.Items:itemsLib:${lastest-version}"
    annotationProcessor "com.github.nekocode.Items:itemsProcessor:${lastest-version}"
}

注意,在 Kotlin 工程中,需要使用 kapt 关键字代替 annotationProcessor 关键字。

使用

使用 BaseItem 能够帮助你把 ViewHolder 的创建和绑定从 Adapter 中提取出来,并且与特定的数据类型绑定。例如你可以为 String 类型的数据创建一个 Item:

public class StringItem extends BaseItem<String, StringItem.Holder, StringItem.Callback> {

    public StringItem(ItemAdapter adapter, int viewType) {
        super(adapter, viewType);
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        final View itemView = inflater.inflate(R.layout.item_string, parent, false);
        final Holder holder = new Holder(itemView);
        holder.button.setOnClickListener(v -> {
            if (getCallback() != null) {
                getCallback().onButtonClick(holder.data);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position, @NonNull String data) {
        holder.data = data;
        holder.textView.setText(data);
    }

    static class Holder extends RecyclerView.ViewHolder {
        private TextView textView;
        private Button button;
        private String data;

        Holder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
            button = itemView.findViewById(R.id.button);
        }
    }

    public interface Callback {
        void onButtonClick(@NonNull String data);
    }
}

Item 提供了很好的拓展能力:

  • 可以使用任意类型的 ViewHolder
  • 可以通过 CallbackViewHolder 设置 UI 事件回调。

接下来你需要创建一个 Adapter 来装载你的所有 Item:

@AdapterClass
public abstract class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemAdapter {
    private final LinkedList mList = new LinkedList();

    @NonNull
    public LinkedList list() {
        return mList;
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @NonNull
    @Override
    public <T> T getData(int position) {
        return (T) mList.get(position);
    }

    /**
     * 定义一个任意名称的方法来返回你想装载的 Item
     */
    @NonNull
    @ItemMethod
    public abstract StringItem stringItem();
}

这个 Adapter 必须实现 ItemAdapter 接口的 getItemCount()getData() 方法。你可以使用任意类型的 Collection(例如上面的 LinkedList)来装载你的数据,这个 Adapter 会通过这两个方法来访问你的数据,然后根据数据的类型来选择对应的 Item 来创建 ViewHolder

在编译期间,Annotation Processor 会为这个 Adapter 生成一个实现类 TestAdapterImpl,你可以通过以下例子来使用这个 Adapter:

// 创建 Adapter 实例
TestAdapter adapter = new TestAdapterImpl();

// 给 Adapter 插入数据
adapter.list().add("Item1");
adapter.list().add("Item2");

// 给 Item 设置 Callback
adapter.stringItem().setCallback(data -> {
    // Button 点击时
});

// 为 RecyclerView 设置 Adapter
recyclerView.setAdapter(adapter);

以上就是这个工具的基础使用。

此外,你还可以让你的单个数据类型绑定多个 Item:

@Adapter
public abstract class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemAdapter {
    // ...

    @NonNull
    @ItemMethod
    public abstract StringItem stringItem();

    @NonNull
    @ItemMethod
    public abstract StringItem2 stringItem2();

    /**
     * 定义一个任意名称的方法来帮助 Adapter 选择绑定了同一数据类型的 Item
     */
    @SelectorMethod
    public int itemForString(int position, @NonNull String data) {
        if (!data.endsWith(2)) {
            return stringItem().getViewType();
        } else {
            return stringItem2().getViewType();
        }
    }
}

最后,还有一个小的 Tip。你可以定义一些 BaseAdapter 来简化你 Adapter 的代码,例如把对集合的操作封装起来,举个例子:

public abstract class BaseArrayListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemAdapter {
    private final ArrayList mList = new ArrayList();

    public ArrayList getList() {
        return mList;
    }

    @NonNull
    @Override
    public <T> T getData(int position) {
        return (T) mList.get(position);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
}

@Adapter
public abstract class TestAdapter extends BaseArrayListAdapter {
    // ...
}

更详细的应用可以参考这个仓库中的 exampleApp 模块。

You might also like...
Android - A ListView adapter with support for multiple choice modal selection
Android - A ListView adapter with support for multiple choice modal selection

MultiChoiceAdapter MultiChoiceAdapter is an implementation of ListAdapter which adds support for modal multiple choice selection as in the native Gmai

Android library to auto-play/pause videos from url in recyclerview.
Android library to auto-play/pause videos from url in recyclerview.

AutoplayVideos Show some ❤️ and star the repo to support the project This library is created with the purpose to implement recyclerview with videos ea

:page_with_curl: [Android Library] Giving powers to RecyclerView
:page_with_curl: [Android Library] Giving powers to RecyclerView

Android library that provides most common functions around recycler-view like Swipe to dismiss, Drag and Drop, Divider in the ui, events for when item

Simplify Adapter creation for your Android ListViews.

FunDapter takes the pain and hassle out of creating a new Adapter class for each ListView you have in your Android app. It is a new approach to custom

EplFootball - Android application displaying EPL teams and their players using MVVM, Coroutines, Flow, Live Data, Retrofit, View Binding, Data Binding, Hilt e.t.c Small, smart and generic adapter for recycler view with easy and advanced data to ViewHolder binding.
Small, smart and generic adapter for recycler view with easy and advanced data to ViewHolder binding.

smart-recycler-adapter Never code any boilerplate RecyclerAdapter again! This library will make it easy and painless to map your data item with a targ

A sample project in Kotlin to demonstrate AndroidX, MVVM, Coroutines, Hilt, Room, Data Binding, View Binding, Retrofit, Moshi, Leak Canary and Repository pattern.

This repository contains a sample project in Kotlin to demonstrate AndroidX, MVVM, Coroutines, Hilt, Room, Data Binding, View Binding, Retrofit, Moshi, Leak Canary and Repository pattern

A Clean Architecture App that uses clean Architecture (app, presentation, domain, data) packages to use coffee items API using MVVM Architecture, Coroutines, Retrofit2, Pagination, Live Data, Data Binding, Hilt , SOLID Principles , Navigation Component , RoomDb.
Use Android Data Binding wih Live Data to glue View Model and Android

Gruop-C Spliff Summary Use Android Data Binding wih Live Data to glue View Model and Android. Asynchronous communications implemented with KotlinX Cor

Handy library to integrate pagination, which allow no data layout, refresh layout, recycler view in one view and easy way to bind pagination in app.
Handy library to integrate pagination, which allow no data layout, refresh layout, recycler view in one view and easy way to bind pagination in app.

Pagination View Handy library to integrate pagination, which allow no data layout, refresh layout, recycler view in one view and easy way to bind pagi

Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. With Kotlin support!
Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. With Kotlin support!

Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. Show some ❤️ 💋 Sweet and short libra

Android view data binding made simple!

DataBinding Android view data binding made simple! A more user friendly docu is coming! This library doesn't use any external library, so it's light w

A blogging mobile application built with Kotlin using MVC design pattern and Take some advantage of Jetpack , View & Data Binding It's a mimic for Tumblr application , But a little prettier than him 😉
A blogging mobile application built with Kotlin using MVC design pattern and Take some advantage of Jetpack , View & Data Binding It's a mimic for Tumblr application , But a little prettier than him 😉

A blogging mobile application built with Kotlin using MVC design pattern and Take some advantage of Jetpack , View & Data Binding It's a mimic for Tum

CMPLR-Native - A blogging mobile application built with Kotlin using MVC design pattern and Take some advantage of Jetpack , View & Data Binding
Recycler-coroutines - RecyclerView Auto Add Data Using Coroutines

Sample RecyclerView Auto Add With Coroutine Colaborator Very open to anyone, I'l

Kotlin way of building RecyclerView Adapter 🧩. You do not have to write RecyclerView Adapters again and again and suffer from handling of different view types. Kiel will help you.

Kiel Kiel is a RecyclerView.Adapter with a minimalistic and convenient Kotlin DSL which provides utility on top of Android's normal RecyclerView.Adapt

A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.
A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.

한국어 No more boilerplate adapters and view holders. Slush will make using RecyclerView easy and fast. The goal of this project is to make RecyclerView,

A data-binding Presentation Model(MVVM) framework for the Android platform.

PLEASE NOTE, THIS PROJECT IS NO LONGER BEING MAINTAINED. As personal time contraints, I am currently unable to keep up. Please use official android da

A data-binding Presentation Model(MVVM) framework for the Android platform.

PLEASE NOTE, THIS PROJECT IS NO LONGER BEING MAINTAINED. As personal time contraints, I am currently unable to keep up. Please use official android da

Comments
  • Any Plan to support auto load more?

    Any Plan to support auto load more?

    • Thank for your library, but I hava some problem about the function about auto load more.
    • Is there any plan to support auto load More?
    • I‘m trying to extends the recyclerview to achieve this function(or a wrapper adapter). Is there any better way to doing this ?
    opened by zubinxiong 3
Releases(1.1.0)
Owner
nekocode
I'm a full-stack engineer and specialize in frontend (android/flutter/web) development.
nekocode
The powerfull Diff Util in Android Recycler View

DiffUtil The powerfull Diff Util in Android Recycler View What is RecyclerView ? RecyclerView is flexible and efficient version of ListView. It is an

Lloyd Dcosta 1 Sep 30, 2021
Renderers is an Android library created to avoid all the boilerplate needed to use a RecyclerView/ListView with adapters.

Renderers Renderers is an Android library created to avoid all the RecyclerView/Adapter boilerplate needed to create a list/grid of data in your app a

Pedro Vicente Gómez Sánchez 1.2k Nov 19, 2022
[] Easy Adapters library for Android

Deprecated Due to the growing use of the RecyclerView and the RecyclerView.Adapter provided adapter class, Easy-Adapter is now deprecated. Whilst the

ribot 425 Nov 25, 2022
Adapter Kit is a set of useful adapters for Android.

Adapter Kit Adapter Kit is a set of useful adapters for Android. The kit currently includes, Instant Adapter Instant Cursor Adapter Simple Section Ada

Ragunath Jawahar 368 Nov 25, 2022
Just like instant coffee, saves 78% of your time on Android's Custom Adapters.

Notice Instant Adapter is now part of an even more awesome Adapter Kit project! Instant Adapter Just like instant coffee, saves 78%* of your time on A

Ragunath Jawahar 232 Nov 25, 2022
This library provides Easy Android ListView Adapters(EasyListAdapter & EasyCursorAdapter) which makes designing Multi-Row-Type ListView very simple & cleaner, It also provides many useful features for ListView.

EasyListViewAdapters Whenever you want to display custom items in listview, then only way to achieve this is to implement your own subclass of BaseAda

Biraj Patel 132 Nov 25, 2022
This library provides GridAdapters(ListGridAdapter & CursorGridAdapter) which enable you to bind your data in grid card fashion within android.widget.ListView, Also provides many other features related to GridListView.

GridListViewAdapters This libarary enables you to implement GridView like card layout within ListView with added capabilites like Paginations, Additio

Biraj Patel 270 Nov 25, 2022
Android library for the adapter view (RecyclerView, ViewPager, ViewPager2)

Antonio Android library for the adapter view (RecyclerView, ViewPager, ViewPager2) Free from implementation of the adapter's boilerplate code ! Reuse

NAVER Z 106 Dec 23, 2022
Vector map library and writer - running on Android and Desktop.

Mapsforge See the integration guide and changelog. And read through how to contribute guidelines. If you have any questions or problems, don't hesitat

mapsforge 1k Jan 2, 2023
Epoxy is an Android library for building complex screens in a RecyclerView

Epoxy Epoxy is an Android library for building complex screens in a RecyclerView. Models are automatically generated from custom views or databinding

Airbnb 8.1k Jan 4, 2023