This Repository simplifies working with RecyclerView Adapter

Related tags

Adapter AutoAdapter
Overview

AutoAdapter

Release Android Arsenal

This Repository simplifies working with RecyclerView Adapter

Gradle:

Add it in your root build.gradle at the end of repositories:

	allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

Add dependency to app gradle:

implementation 'com.github.Zuluft:AutoAdapter:v2.4.1'
annotationProcessor 'com.github.Zuluft:AutoAdapter:v2.4.1'

Simple Sample:

Step 1:

Create layout xml file, for example item_footballer.xml which contains TextViews with ids tvName, tvNumber, tvClub and ImageView with id ivDelete

Step 2 (Optional):

create model, that you want to be drawn on above created layout:

public final class FootballerModel {
    private final String name;
    private final int number;
    private final String club;

    public FootballerModel(final String name,
                           final int number,
                           final String club) {
        this.name = name;
        this.number = number;
        this.club = club;
    }

    public String getName() {
        return name;
    }

    public int getNumber() {
        return number;
    }

    public String getClub() {
        return club;
    }
}

Step 3:

Create 'Renderer' class in the following way:

   @Render(layout = R.layout.item_footballer,
        views = {
                @ViewField(
                        id = R.id.tvName,
                        name = "tvName",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvNumber,
                        name = "tvNumber",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvClub,
                        name = "tvClub",
                        type = TextView.class
                )
        })
public class FootballerRenderer{
        
}

@Render annotation is needed to generate ViewHolder for this Renderer by annotation processor. Inside @Render annotation layout value is an itemView layout id and @ViewFields are containing information about the views in this layout. Name of the generated ViewHolder will be RendererClassName+'ViewHolder', in this case FootballerRendererViewHolder

Step 4:

Rebuild the project. Rebuilding generates ViewHolder class (FootballerRendererViewHolder), that we use in Step 5.

Step 5:

Extend your FootballerRenderer by Renderer and pass newly generated FootballerRendererViewHolder as a generic type:

@Render(layout = R.layout.item_footballer,
        views = {
                @ViewField(
                        id = R.id.tvName,
                        name = "tvName",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvNumber,
                        name = "tvNumber",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvClub,
                        name = "tvClub",
                        type = TextView.class
                )
        })
public class FootballerRenderer
        extends
        Renderer<FootballerRendererViewHolder> {

    public final FootballerModel footballerModel;

    public FootballerRenderer(final FootballerModel footballerModel) {
        this.footballerModel = footballerModel;
    }

    @Override
    public void apply(@NonNull final FootballerRendererViewHolder vh) {
        final Context context = vh.getContext();
        vh.tvName.setText(footballerModel.getName());
        vh.tvClub.setText(footballerModel.getClub());
        vh.tvNumber.setText(context.getString(R.string.footballer_number_template,
                footballerModel.getNumber()));
    }
}

As you see generated FootballerRendererViewHolder has tvName, tvClub, tvNumber fields.

Step 6:

  ...
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
	...
	mAutoAdapter = AutoAdapterFactory.createAutoAdapter();
        mAutoAdapter.addAll(Stream.of(getFootballers()).map(FootballerRenderer::new)
                .collect(Collectors.toList()));
        mRecyclerView.setAdapter(mAutoAdapter);
    }


    private List<FootballerModel> getFootballers() {
        return Arrays.asList(
                new FootballerModel("Luis Suarez", 9, "Barcelona"),
                new FootballerModel("Leo Messi", 10, "Barcelona"),
                new FootballerModel("Ousmane Dembele", 11, "Barcelona"),
                new FootballerModel("Harry Kane", 9, "Tottenham Hotspur"),
                new FootballerModel("Dele Alli", 20, "Tottenham Hotspur"),
                new FootballerModel("Alexis Sanchez", 7, "Arsenal")
        );
    }

This line Stream.of(getFootballers()).map(FootballerRenderer::new).collect(Collectors.toList()) converts FootballerModel to FootballerRenderer using Stream

Mmm... What If I want to have heterogeneous items and layouts inside RecyclerView ?

AutoAdapter's working perfectly with heterogeneous items. You can add any descedent of Renderer to AutoAdapter, for example it's not a problem to write the following:

...
mAutoAdapter.add(new FootballerRenderer());
mAutoAdapter.add(new BasketballerRenderer());
mAutoAdapter.add(new BoxerRenderer());
....

They all will draw their own layout.

How to add OnClickListener to itemView ?

AutoAdapter has clicks method, it has one required argument Renderer class, one optional argument child view id and returns Rx2 Observable with ItemInfo as generic type. ItemInfo has 3 public final fields: position, renderer, viewHolder.

...
mAutoAdapter.clicks(FootballerRenderer.class)
                .map(itemInfo -> itemInfo.renderer)
                .map(renderer -> renderer.footballerModel)
                .subscribe(footballerModel ->
                        Toast.makeText(this,
                                footballerModel.getName(), Toast.LENGTH_LONG)
                                .show());
...
...
mAutoAdapter.clicks(FootballerRenderer.class, R.id.ivDelete)
                .map(itemInfo -> itemInfo.position)
                .subscribe(position -> {
                    mAutoAdapter.remove(position);
                    mAutoAdapter.notifyItemRemoved(position);
                });
...

SortedAutoAdapter Sample:

@Render(layout = R.layout.item_footballer,
        views = {
                @ViewField(
                        id = R.id.tvName,
                        name = "tvName",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvNumber,
                        name = "tvNumber",
                        type = TextView.class
                ),
                @ViewField(
                        id = R.id.tvClub,
                        name = "tvClub",
                        type = TextView.class
                )
        })
public class FootballerOrderableRenderer
        extends
        OrderableRenderer<FootballerOrderableRendererViewHolder> {

    public final FootballerModel footballerModel;

    public FootballerOrderableRenderer(final FootballerModel footballerModel) {
        this.footballerModel = footballerModel;
    }

    @Override
    public void apply(final FootballerOrderableRendererViewHolder vh) {
        final Context context = vh.getContext();
        vh.tvName.setText(footballerModel.getName());
        vh.tvClub.setText(footballerModel.getClub());
        vh.tvNumber.setText(context.getString(R.string.footballer_number_template,
                footballerModel.getNumber()));
    }

    @Override
    public int compareTo(@NonNull OrderableRenderer item) {
        return Integer.valueOf(footballerModel.getNumber())
                .compareTo(getFootballerModel(item).getNumber());
    }

    private FootballerModel getFootballerModel(@NonNull final OrderableRenderer orderableRenderer) {
        return ((FootballerOrderableRenderer) orderableRenderer).footballerModel;
    }

    @Override
    public boolean areContentsTheSame(@NonNull OrderableRenderer item) {
        final FootballerModel otherFootballer = getFootballerModel(item);
        return footballerModel.getClub().equals(otherFootballer.getClub())
                && footballerModel.getNumber() == otherFootballer.getNumber();
    }

    @Override
    public boolean areItemsTheSame(@NonNull OrderableRenderer item) {
        return footballerModel.getName().equals(getFootballerModel(item).getName());
    }
}
public class SortedAutoAdapterSampleActivity
        extends
        AppCompatActivity {

    private RecyclerView mRecyclerView;
    private SortedAutoAdapter mSortedAutoAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                LinearLayoutManager.VERTICAL));
        mSortedAutoAdapter = AutoAdapterFactory.createSortedAutoAdapter();
        mSortedAutoAdapter.clicks(FootballerOrderableRenderer.class)
                .map(itemInfo -> itemInfo.renderer)
                .map(renderer -> renderer.footballerModel)
                .subscribe(footballerModel ->
                        Toast.makeText(this,
                                footballerModel.getName(), Toast.LENGTH_LONG)
                                .show());
        mSortedAutoAdapter.clicks(FootballerOrderableRenderer.class, R.id.ivDelete)
                .map(itemInfo -> itemInfo.position)
                .subscribe(position ->
                        mSortedAutoAdapter.remove(position));
        mSortedAutoAdapter.updateAll(Stream.of(getFootballers())
                .map(FootballerOrderableRenderer::new)
                .collect(Collectors.toList()));
        mRecyclerView.setAdapter(mSortedAutoAdapter);
    }

    private List<FootballerModel> getFootballers() {
        return Arrays.asList(
                new FootballerModel("Luis Suarez", 9, "Barcelona"),
                new FootballerModel("Leo Messi", 10, "Barcelona"),
                new FootballerModel("Ousmane Dembele", 11, "FC Barcelona"),
                new FootballerModel("Harry Kane", 9, "Tottenham Hotspur"),
                new FootballerModel("Dele Alli", 20, "Tottenham Hotspur"),
                new FootballerModel("Alexis Sanchez", 7, "Arsenal")
        );
    }
}
You might also like...
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

Renderers is an Android library created to avoid all the boilerplate needed to use a RecyclerView/ListView with adapters.
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

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

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

Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

EventBus EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components decouples event s

Wrapper around the android Camera class that simplifies its usage

EasyCamera Wrapper around the android Camera class that simplifies its usage (read more about the process) Usage: // the surface where the preview wil

Wrapper around the android Camera class that simplifies its usage

EasyCamera Wrapper around the android Camera class that simplifies its usage (read more about the process) Usage: // the surface where the preview wil

A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.
A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lo

Greatly simplifies the complexities of Kotlin's reflection of Java

CatReflect 这是一个可以极大简化 Java 反射的复杂操作的工具,适用于 Kotlin & Java This is a tool that grea

Repository ini berguna untuk menyimpan kode yang dibutuhkan untuk membuat sebuah Aplikasi Android yang memiliki ListView yang menggunakan Custom Adapter dan Mengambil data dari Database secara CRUD.

AndroidListView Repository ini berguna untuk menyimpan kode yang dibutuhkan untuk membuat sebuah Aplikasi Android yang memiliki ListView yang mengguna

 An adapter which could be used to achieve a parallax effect on RecyclerView.
An adapter which could be used to achieve a parallax effect on RecyclerView.

android-parallax-recycleview Integration Step 1. Add the JitPack repository to your build file repositories { maven { url "https://jitpack

Android library defining adapter classes of RecyclerView to manage multiple view types
Android library defining adapter classes of RecyclerView to manage multiple view types

RecyclerView-MultipleViewTypeAdapter RecyclerView adapter classes for managing multiple view types Release Note [Release Note] (https://github.com/yqr

An Adapter that allows a RecyclerView to be split into Sections with headers and/or footers. Each Section can have its state controlled individually.
An Adapter that allows a RecyclerView to be split into Sections with headers and/or footers. Each Section can have its state controlled individually.

⚠️ Archived: this repository is no longer going to be maintained. SectionedRecyclerViewAdapter An Adapter that allows a RecyclerView to be split into

Create a new adapter for a RecyclerView or ViewPager is now much easier.

Efficient Adapter for Android Create a new adapter for a RecyclerView or ViewPager is now much easier. Overview Create a list of elements into a Recyc

Rx based RecyclerView Adapter
Rx based RecyclerView Adapter

RxRecyclerAdapter Rx based generic RecyclerView Adapter Library. How to use it? Example! Enable Databinding by adding these lines to your build.gradle

Generic RecyclerView adapter

Generic RecyclerView Adapter. Lightweight library which simplifies creating RecyclerView adapters and illuminates writing boilerplate code. Creating a

RecyclerView Adapter Library with different models and different layouts as convenient as possible.
RecyclerView Adapter Library with different models and different layouts as convenient as possible.

RecyclerView Presenter Convenience library to handle different view types with different presenters in a single RecyclerView. How to install repositor

Comments
  • Suddenly AutoAdapterFactory vanished

    Suddenly AutoAdapterFactory vanished

    One minute ago AutoAdapterFactory was working just fine. After 1 minute, yes just 1 minute, it vanished. Other parts of the library stays, just AutoAdapterFactory. It ruined my project. Please tell me how to fix it.

    opened by fkucukapps 2
  • Thoughts and feature requests

    Thoughts and feature requests

    I have adopted this library for my latest project and it is truly amazing. It shortens the time I spent to build recyclerview adapters dramatically. Easy to use, low learning curve. Simply fantastic!

    However I have a few feature requests for future releases and I will be waiting impatiently for those.

    1. Long click listener
    2. Swipe listener
    3. Expandable recyclerview

    I don't know if it is the right place to make requests, and I even don't know if I have right to make requests. However, I think this kind of library was what the beginners, and developers who need rapid development solutions needed and you provided it! Thank you!

    opened by fkucukapps 1
Owner
George Dzotsenidze
George Dzotsenidze
Create a new adapter for a RecyclerView or ViewPager is now much easier.

Efficient Adapter for Android Create a new adapter for a RecyclerView or ViewPager is now much easier. Overview Create a list of elements into a Recyc

Stan Kocken 423 Sep 16, 2022
Rx based RecyclerView Adapter

RxRecyclerAdapter Rx based generic RecyclerView Adapter Library. How to use it? Example! Enable Databinding by adding these lines to your build.gradle

Ahmed Rizwan 193 Jun 18, 2022
Generic RecyclerView adapter

Generic RecyclerView Adapter. Lightweight library which simplifies creating RecyclerView adapters and illuminates writing boilerplate code. Creating a

Leonid Ustenko 77 Dec 24, 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
The bullet proof, fast and easy to use adapter library, which minimizes developing time to a fraction...

FastAdapter The FastAdapter is here to simplify creating adapters for RecyclerViews. Don't worry about the adapter anymore. Just write the logic for h

Mike Penz 3.7k Jan 8, 2023
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

Manuel Peinado Gallego 855 Nov 11, 2022
A slim & clean & typeable Adapter without# VIEWHOLDER

PLEASE NOTE, THIS PROJECT IS NO LONGER BEING MAINTAINED First At A Glance :) Intro A slim & clean & typeable Adapter without# VIEWHOLDER Features No V

lin 940 Dec 30, 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
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

Ami Goldenberg 287 Dec 22, 2022
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

Manne Öhlund 405 Dec 30, 2022