• Stars
    star
    252
  • Rank 161,312 (Top 4 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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 模块。

More Repositories

1

CameraFilter

📷 Realtime camera filters on android.
Java
2,129
star
2

create-android-kotlin-app

Create kotlin android project with one line of command.
Kotlin
1,596
star
3

Badge

:octocat: Drawable of badge.
Java
956
star
4

Emojix

Implementation of iOS style emoji on android.
Java
586
star
5

MusicVisualization

Some music visualization demos on android.
Java
488
star
6

Murmur

📻 A third-party android client of DoubanFM.
Kotlin
453
star
7

DividerDrawable

Help to layout and draw dividers on android views.
Java
452
star
8

ResourceInspector

A debug tool to inspect used layout files of current Activity.
Java
349
star
9

Meepo

A router generator on android, similar to retrofit.
Java
316
star
10

android-parcelable-intellij-plugin-kotlin

Plugin which generates Android Parcelable boilerplate code for kotlin's class.
Java
300
star
11

TriangulationDrawable

Low Ploy Triangulation Animation on Android.
Java
255
star
12

JarFilterPlugin

Help exclude classes before building the JAR into Android DEX archives.
Kotlin
222
star
13

ToolbarIndicator

A toolbar indicator for android, likes twitter's.
Java
221
star
14

tornaREST

A simple RESTful Web Service built with Tornado.
Python
212
star
15

doubanfm-py

📻 豆瓣 FM 第三方红心频道播放器
Python
132
star
16

zhihuSayHi

[Unmaintained] Say Hi to your new followers in Zhihu.
Python
118
star
17

RxActivityResult

This is a library that can help you to receive results from startActivityForResult() as an Observable.
Java
76
star
18

wx_sniffer

抓取微信公众号文章阅读数、点赞数
Python
74
star
19

MethodTracerCli

A command-line interface of Android Studio's method tracer.
Java
61
star
20

use-shared-state

React hook for sharing state or notifying event between components. Just like the widget controller in Flutter.
TypeScript
58
star
21

weixin_vote

使用 Tornado 开发的微信公众平台投票系统
JavaScript
44
star
22

h5pay-flutter

A H5/HTML5 payment (such as Alipay, WeChat-Pay) plugin for flutter.
Dart
42
star
23

ASM-Systrace

A plugin to inject tracing code to specified methods.
Java
37
star
24

GradleImportAar

This project demonstrates how to import aar libs to a pure java gradle module.
Kotlin
32
star
25

v2ray-docker

Docker image of v2ray(ws + tls) & caddy2.
HTML
26
star
26

nekocode.cn

The repository that hosted the source files of nekocode.cn
TypeScript
26
star
27

Websocket-Adb-Forward

Create websocket connection between your mobile and computer via USB.
Java
24
star
28

win_penetration

Penetration testing on windows(7 or 8)
PowerShell
24
star
29

codelabs-hugo-theme

A hugo theme for building codelabs website.
JavaScript
24
star
30

blur-using-textureview

Create blur effect on android by using texture view.
Java
22
star
31

gradle-dependency-graph

Visualize the dependency graph of gradle project.
TypeScript
19
star
32

project-gallery

A webpage to show the projects you have open sourced in github.
JavaScript
18
star
33

antd-dayjs-vite-plugin

A Vite port of antd-dayjs-webpack-plugin. Day.js vite plugin for Ant Design (antd).
TypeScript
18
star
34

drag-down-to-pop-flutter

A page transition which supports drag-down-to-pop gesture.
Dart
17
star
35

leetcode-solutions

My solutions of leetcode's problems.
Java
16
star
36

docker-android

Docker image for Android builds.
13
star
37

neko-gallery

A cyberpunk style gallery website for listing all your open sourced projects.
Svelte
12
star
38

Unity3D-TextureAtlasSlicer-Cocos2d-x

Simple and fast tool to import Cocos2d-x spritesheets (TextureAtlas) into Unity3D.
C#
12
star
39

nekocode.github.io

The repository to host website nekocode.cn.
HTML
11
star
40

TachieTransition

Tachie transition, written in renderscript.
Java
10
star
41

github_email_crawler

A tool for crawling emails from github.com.
TypeScript
9
star
42

resume

My personal resume.
CSS
8
star
43

Bangcle-Crypto-Wrapper

Encrypt your keys at build time using the Bangcle WhiteCrypto tools.
Java
7
star
44

finding_self_starred

寻找某人自己 Star 自己的仓库
Python
6
star
45

resty-limit-docker

An openresty/nginx based api gateway that can limit max count of connected IPs and traffic speed of network.
Shell
5
star
46

nbackdoor

A simple backdoor script on windows.
Python
4
star
47

Taskkiller

在后台静默监控并杀死指定进程的工具
C++
4
star
48

typescript-graphql-over-prisma

This example demonstrates how to build a GraphQL server over the Prisma.
TypeScript
4
star
49

DepAnPlugin

A gradle plugin to extract the bytecode and dependency information (between classes, fields and methods) of your Android project.
Kotlin
4
star
50

FScript0.15

A simple text adventure game engine.
C++
3
star
51

FScript0.2

A simple text adventure game engine.
C
2
star
52

FScriptIDE

A simple IDE for FScript 0.1x.
C++
2
star
53

wcmovie_test

「卧槽电影」公众号营销用测试游戏
Python
2
star
54

BattleBeats

A danmaku game just like 'BeatHazard'.
C++
1
star
55

svelte-ts-scss-template

Template for building applications with Svelte.
JavaScript
1
star
56

cxi

批处理 mask 位图,转换为带 alpha 的 png 图片
C++
1
star
57

caddy-iplimit

A caddy plugin for limiting the max number of connected IPs.
Go
1
star
58

vimrc

.vimrc for python dev
Vim Script
1
star
59

mqtt_test

mqtt test in python
Python
1
star
60

Hidden-Apis-Calling-Demo

It demonstrates a simple way to directly call hidden apis of android sdk.
Java
1
star