Life of Apps

ListView to RecyclerView - Key Code Changes

There are several good blog posts that explain the concept and theory of a RecyclerView and how to implement it. This post is mainly looks at the key code changes required when moving from ListView to RecyclerView.

1. Add the following to the build.gradle under the app module
    dependencies {
        compile ''

2. Probably the biggest change is the adapter from BaseAdapter or ArrayAdapter to  RecyclerView.Adapter.
public class MainViewAdapter  extends RecyclerView.Adapter<MainViewAdapter.PostViewHolder>

3. If like me you had been using an ArrayAdapter , make the arrays into lists as the new adapter code looks more elegant with them

4. The ViewHolder class becomes a must - it is a public static class inside the adapter that holds the UI items such as TextViews

5. UI items get added to a view holder instead of a View

6. Implement custom ViewHolder classes such as PostViewHolder that I have mentioned above to hold the layout that you need (e.g. TextViews, ImageView etc. that make a row in a list)

7. getView method in adapter is replaced by onCreateViewHolder - holder is created here, onBindViewHolder - UI attributes such as TextView.setText happen here

8. XML layout file has to include a RecyclerView instead of a ListView

9. Usually a CardView is used for the "list row" inside the RecyclerView. It can be made to look like a list with the right tweaks to cardElevation

10. Handling clicks is a big pain as there is no onItemClick like lists and OnItemTouchListener requires implementing several methods. The workaround is to create an interface like ItemClickListener and attach it to a view. This article shows how to do it along with a detailed tutorial on other aspects of the RecyclerView.


Visit for apps developed by Danesh

No comments :

Post a Comment

Leave a Comment...