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

Overview

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 RecyclerView or ViewPager is not that easy for a beginner, and repetitive for others. The goal of this library is to simplify that for you.

How does it work?

Create a class ViewHolder (BookViewHolder for example). The method updateView will be call with the object, when an update of your view is require:

public class BookViewHolder extends EfficientViewHolder<Book> {
    public BookViewHolder(View itemView) {  super(itemView); }

    @Override
    protected void updateView(Context context, Book object) {
        TextView textView = findViewByIdEfficient(R.id.title_textview);
        textView.setText(object.getTitle());
		// or just
		setText(R.id.title_textview, object.getTitle());
    }
}

Give this ViewHolder class to the constructor of the adapter (SimpleAdapter) of your RecyclerView, with the resource id of your item view and the list of objects:

EfficientRecyclerAdapter<Plane> adapter = new EfficientRecyclerAdapter<Plane>(R.layout.item_book, BookViewHolder.class, listOfBooks);
recyclerView.setAdapter(adapter);

And that's it!

It's also working with a ViewPager:

EfficientPagerAdapter<Plane> adapter = new EfficientPagerAdapter<Plane>(R.layout.item_book, BookViewHolder.class, listOfBooks);
viewPager.setAdapter(adapter);

Other features

Heterogenous list

For a list of different kind of objects, layout, viewholder…

EfficientRecyclerAdapter adapter = new EfficientRecyclerAdapter(generateListObjects()) {
    @Override
    public int getItemViewType(int position) {
        if (get(position) instanceof Plane) {
            return VIEW_TYPE_PLANE;
        } else {
            return VIEW_TYPE_BOOK;
        }
    }

    @Override
    public Class<? extends EfficientViewHolder> getViewHolderClass(int viewType) {
        switch (viewType) {
            case VIEW_TYPE_BOOK:
                return BookViewHolder.class;
            case VIEW_TYPE_PLANE:
                return PlaneViewHolder.class;
            default:
                return null;
        }
    }

    @Override
    public int getLayoutResId(int viewType) {
        switch (viewType) {
            case VIEW_TYPE_BOOK:
                return R.layout.item_book;
            case VIEW_TYPE_PLANE:
                return R.layout.item_plane;
            default:
                return 0;
        }
    }
};

Efficient findViewById()

Because findViewById(int) is CPU-consuming (this is why we use the ViewHolder pattern), this library use a findViewByIdEfficient(int id) into the ViewHolder class.

You can use it like a findViewById(int id) but the view return will be cached to be returned into the next call.

Your view id should be unique into your view hierarchy, but sometimes is not that easy (with an include for example). It's now easier to find a subview by specify the parent of this subview with findViewByIdEfficient(int parentId, int id) to say "the view with this id into the parent with this id".

Let the element be clickable

Your ViewHolder class can override the method isClickable() to tell is this element is clickable or not.

By default, the view is clickable if you have a listener on your adapter.

Proguard

This library includes the proguard configuration file. If you want to add it manually:

-keepclassmembers public class * extends com.skocken.efficientadapter.lib.viewholder.EfficientViewHolder {
    public <init>(...);
}

Gradle

dependencies {
    compile 'com.skocken:efficientadapter:2.4.0'
}

Android Support library

If you are still using the deprecated Android Support Library (instead of AndroidX), please use the dependency 2.3.X instead.

License

Contributing

Please fork this repository and contribute back using pull requests.

Any contributions, large or small, major features, bug fixes, additional language translations, unit/integration tests are welcomed and appreciated but will be thoroughly reviewed and discussed.

Comments
  • Use ViewHolder as InnerClass of a Adapter

    Use ViewHolder as InnerClass of a Adapter

    some time,we need the ViewHolder to be a innerClass of a Adapter ,incase to share the variable of it。 so here is the code we modified to support this feature。it both support single ViewHolder class or as innerClass in Adapter。

    AdapterHelper.class

    <T extends EfficientViewHolder> EfficientViewHolder generateViewHolder(View v,
                                                                           Class<T> viewHolderClass, EfficientRecyclerAdapter adapter) {
        Constructor<?>[] constructors = viewHolderClass.getDeclaredConstructors();
    
        if (constructors == null)
            return null;
    
        for (Constructor<?> constructor : constructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (parameterTypes == null)
                continue;
    
            try {
                if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(View.class)) {
                    Object viewHolder = constructor.newInstance(v);
                    return (EfficientViewHolder) viewHolder;
                }
    
                if (parameterTypes.length == 2 && parameterTypes[1].isAssignableFrom(View.class)) {
                    Object viewHolder = constructor.newInstance(adapter, v);
                    return (EfficientViewHolder) viewHolder;
                }
            } catch (Exception e) {
                Log.e("ViewHolder init error", e.getMessage());
                throw new RuntimeException(
                        "Impossible to instantiate "
                                + viewHolderClass.getSimpleName(), e);
            }
        }
    
        return null;
    }
    

    EfficientRecyclerAdapter.class

    @Override
    public EfficientViewHolder generateViewHolder(View v, int viewType) {
        Class<? extends EfficientViewHolder> viewHolderClass = getViewHolderClass(viewType);
        if (viewHolderClass == null) {
            mBaseAdapter.throwMissingViewHolder(viewType);
            return null;
        }
        return mBaseAdapter.generateViewHolder(v, viewHolderClass, this);
    }
    
    opened by zhexian 8
  • Syntactic sugar

    Syntactic sugar

    how about reduce more code?

    in EfficientViewHolder Class,add the code below

    public void setText(int viewId, String text) {
        TextView tv = findViewByIdEfficient(viewId);
        tv.setText(text);
    }
    
    public void setTextColor(int viewId, int textColor) {
        TextView view = findViewByIdEfficient(viewId);
        view.setTextColor(textColor);
    }
    
    
    public void setImageResource(int viewId, int resId) {
        ImageView view = findViewByIdEfficient(viewId);
        view.setImageResource(resId);
    }
    
    public void setVisible(int viewId, boolean visible) {
        View view = findViewByIdEfficient(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
    }
    
    public void setTag(int viewId, Object tag) {
        View view = findViewByIdEfficient(viewId);
        view.setTag(tag);
    }
    
    public void setTag(int viewId, int key, Object tag) {
        View view = findViewByIdEfficient(viewId);
        view.setTag(key, tag);
    }
    
    public void setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = findViewByIdEfficient(viewId);
        view.setOnClickListener(listener);
    }
    

    the result:

    before:

                    ((TextView)findViewByIdEfficient(R.id.textView_teacher_syncHomeWork_content)).setText(object.getQueContent());
            ((TextView) findViewByIdEfficient(R.id.textView_teacher_syncHomeWork_answerTime))
                    .setText("平均答题时间:" + DatetimeUtils.formatDateForClock(Convert.toInt(object.getAnswerAvgTime())));
    
            findViewByIdEfficient(R.id.relativeLayout_teacher_syncHomeWork_container).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    ToastUtil.shortShow(context, "点击了:" + object.getQueId());
                }
            });
    

    after:

            setText(R.id.textView_teacher_syncHomeWork_content, object.getQueContent());
            setText(R.id.textView_teacher_syncHomeWork_answerTime, "平均答题时间:" + DatetimeUtils.formatDateForClock(Convert.toInt(object.getAnswerAvgTime())));
    
            setOnClickListener(R.id.relativeLayout_teacher_syncHomeWork_container, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtil.shortShow(context, "点击了:" + object.getQueId());
                }
            });
    

    thanks to your nice project

    opened by zhexian 8
  • adapter.setOnItemLongClickListener Not Working

    adapter.setOnItemLongClickListener Not Working

    I seems that the LongClick method of the simpleAdapter is not working as it is supposed to, the simple click listener is working fine. And is there any way to add onItemTouchListener as well on the Adapter.

    Thanks in advance

    opened by Rohail 8
  • get the position of a View

    get the position of a View

    Is it possible that this adapter "breaks" the RecyclerView.LayoutManager.getPosition(View view) ? It is always returning -1. Maybe I'm not doing it correctly but I think I am.

    opened by nitrico 3
  • Sending References to the Holder

    Sending References to the Holder

    How to send custom objects to holder e.g reference to my Fragment object so that i can call public methods from within the Holder, any way to achieve that ? Sorry for the inconvenience :(

    opened by Rohail 2
  • item listener is called twice.

    item listener is called twice.

    Hi, Thanks for your library. But when i clicked the recycleview's item, i found the item listener was called twice. So I read the library code, i found you set TWO times call back in the ViewHolderClickListener .

    opened by OilLyu 1
  • Prevent calling notifyItemXXXX.

    Prevent calling notifyItemXXXX.

    Would be possible to add setNotifyOnChange(bool)?

    I use a SwipeRefreshLayout so i need to clear the current adapter and add all the items back and when i use adapter.clear() and then addAll() a small flickering happends.

    opened by Wolftein 1
  • 【improve】 support head、footView

    【improve】 support head、footView

    add custom headView、footView

    public class HeadFootRecyclerAdapter<T> extends EfficientRecyclerAdapter<T> {
        private static final int HEAD_VIEW_TYPE = 3300;
        private static final int FOOT_VIEW_TYPE = HEAD_VIEW_TYPE + 1;
    
        private View mHeadView;
        private View mFootView;
    
        public HeadFootRecyclerAdapter(List<T> objects) {
            super(objects);
        }
    
        public HeadFootRecyclerAdapter(int layoutResId, Class<? extends EfficientViewHolder<? extends T>> viewHolderClass, List<T> objects) {
            super(layoutResId, viewHolderClass, objects);
        }
    
        public void setHeadView(View headView) {
            mHeadView = headView;
            notifyDataSetChanged();
        }
    
        public void setFootView(View footView) {
            mFootView = footView;
            notifyDataSetChanged();
        }
    
        public boolean hasHeadView() {
            return mHeadView != null;
        }
    
        public boolean hasFootView() {
            return mFootView != null;
        }
    
        public void removeHeadView() {
            if (!hasHeadView()) return;
    
            mHeadView = null;
            notifyDataSetChanged();
        }
    
        public void removeFootView() {
            if (!hasFootView()) return;
    
            mFootView = null;
            notifyDataSetChanged();
        }
    
        @Override
        public int getItemCount() {
            int count = super.getItemCount();
    
            if (mHeadView != null)
                count++;
    
            if (mFootView != null)
                count++;
    
            return count;
        }
    
        public int getRealCount() {
            return super.getItemCount();
        }
    
        public int getRealPosition(int position) {
            if (mHeadView != null) {
                position--;
            }
    
            return position;
        }
    
        @Override
        public int getItemViewType(int position) {
            if (mHeadView != null && position == 0) {
                return HEAD_VIEW_TYPE;
            }
    
            if (mFootView != null && position == getItemCount() - 1) {
                return FOOT_VIEW_TYPE;
            }
    
            return super.getItemViewType(position);
        }
    
        @Override
        public EfficientViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == HEAD_VIEW_TYPE && mHeadView != null) {
                return new EfficientViewHolder(mHeadView) {
                    @Override
                    protected void updateView(Context context, Object object) {
    
                    }
                };
            }
    
            if (viewType == FOOT_VIEW_TYPE && mFootView != null) {
                return new EfficientViewHolder(mFootView) {
                    @Override
                    protected void updateView(Context context, Object object) {
    
                    }
                };
            }
    
            return super.onCreateViewHolder(parent, viewType);
        }
    
        @Override
        public void onBindViewHolder(EfficientViewHolder viewHolder, int position) {
            int viewType = getItemViewType(position);
    
            if (viewType == HEAD_VIEW_TYPE || viewType == FOOT_VIEW_TYPE) return;
    
    
            position = getRealPosition(position);
            super.onBindViewHolder(viewHolder, position);
        }
    }
    
    
    
    opened by xiaobaDev 0
Owner
Stan Kocken
Stan Kocken
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

Gustavo Pagani 1.7k Dec 21, 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
This Repository simplifies working with RecyclerView Adapter

AutoAdapter This Repository simplifies working with RecyclerView Adapter Gradle: Add it in your root build.gradle at the end of repositories: allproj

George Dzotsenidze 151 Aug 15, 2021
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
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
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
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
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

Krupen Ghetiya 989 Nov 17, 2022
: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

Nishant Srivastava 644 Nov 20, 2022
Android auto scroll viewpager or viewpager in viewpager

Android Auto Scroll ViewPager ViewPager which can auto scrolling, cycling, decelerating. ViewPager which can be slided normal in parent ViewPager. Att

Trinea 1.7k Dec 10, 2022
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

Rakshak R.Hegde 180 Nov 18, 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
BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing).

BindsAdapter BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing). Installation

Jintin 5 Jul 30, 2022
The flexible, easy to use, all in one drawer library for your Android project. Now brand new with material 2 design.

MaterialDrawer ... the flexible, easy to use, all in one drawer library for your Android project. What's included ?? • Setup ??️ • Migration Guide ??

Mike Penz 11.6k Dec 27, 2022