Creating custom RecyclerView adapter

with multiple view items example

Creating custom,RecyclerView has been the defacto for viewing lists in android. The stable overall performance and the capacity to plugin any function right into a listing without breaking a sweat made it the developer favourite. Ultimately changing Listviews from being the same old manner of showing lists in android packages. What makes the RecyclerView the go-to library while considering lists?

For years the way developers used to think about viewing lists changed into quite truthful. Having a linear set of perspectives and without a doubt populating it with the records, sounds like the jobs executed! But matters get genuinely messy when this length of the list grows and effs up the consumer enjoy of the app with the aid of losing frames and sloppy scroll behavior. RecyclerView turned into added with this magical formulation of reusing the views with out compromising the overall performance and reminiscence. It made animations easy to implement on these lists for the addition or elimination of objects, made it rattling clean to construct lists that supported grids, horizontal or vertical scrolling or occasion scrolling the entire issue upside down (pssst… chats)!

How does a RecyclerView work?

Having a deeper knowledge of the RecyclerView and the RecyclerViewAdapter will help lots in writing efficient code. Let’s see what makes RecyclerView amazing. At the center, the view is known for it’s recycling capacity of toddler views that assist reduce reminiscence usage (That’s wherein the call comes from). At first, RecyclerView initializes a fixed of child views to display a sure quantity of contents within the list to fill the viewport of the screen. Once the user begins scrolling, the view which receives beyond the screen boundary is used to repopulate and reused at the alternative cease, this is completed through the Adapter.

Let’s take an instance. Consider a RecyclerView showing a list of contacts, wherein each contact is displayed as a card. If the screen has the dimensions to fit five such touch playing cards, recycler view keeps a decrease sure of some greater cards and initializes it to give a easy scrolling effect. So, if the RecyclerView has created a hard and fast of 7 perspectives geared up to show regardless of even supposing the data is manner large than that, and the viewport can suit 5, once the user starts scrolling, the sixth, and 7th come into the display at the same time as the views 1 and 2 exits the display. These views 1 and a pair of are then used to repopulate with the data and added returned to the list’s bottom making it enter as the eighth and 9th card within the view.

Creating a Custom RecyclerView Adapter

Before attaching a Custom Adapter to the RecyclerView, make sure you’ve got protected the RecyclerView view tags inside the format (xml) file.

1.

And, We need one greater format report so that you can be used as the view for each row or item inside the RecyclerView, Simply to use as a template. We’ll take an instance of a easy touch list. Create a new XML format record in res/format/ together with your preferred format layout.

1.

2. 9. 15. 21.

We want to create a POJO elegance (Plain Old Java Object) to represent each records item as an item whilst passing it all the way down to the adapter, with out dropping a sweat, android studio helps to add all the essential getters, setters and constructors into the class via shortcuts (ALT + INSERT) after giving the basic info. Create a Java Class to maintain the essential data regarding the statistics objects.

1. public class Contact { 2. 3. private String name; 4. private String number; 5. 6. public Contact(String name, String number) { 7. this.name = name; 8. this.number = number; 9. } 10. 11. public String getName() { 12. return name; 13. } 14. 15. public void setName(String name) { 16. this.name = name; 17. } 18. 19. public String getNumber() { 20. return number; 21. } 22. 23. public void setNumber(String number) { 24. this.number = number; 25. } 26. }

Custom RecyclerView

Now Let’s start working on the custom Adapter for the RecyclerView. Create a cutting-edge Java Class extending the RecyclerView.Adapter and override the following strategies from the determine elegance. We additionally want to create a nested sub-class extending the RecyclerView.ViewHolder which enables to create ViewHolders which populates facts to the views present within the recyclerView. Once we cord up the whole thing, our Custom adapter will appearance something similar to this.

public class MyAdapter extendsRecyclerView.Adapter { // List to store all the contact details private ArrayList contactsList; private Context mContext; // Counstructor for the Class public VideoListAdapter(ArrayList contactsList, Context context) { this.contactsList = contactsList; this.mContext = context; } // This method creates views for the RecyclerView by inflating the layout // Into the viewHolders which helps to display the items in the RecyclerView @Override public ContactHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); // Inflate the layout view you have created for the list rows here View view = layoutInflater.inflate(R.layout.contact_list_item, parent, false); return new ContactHolder(view); } @Override public int getItemCount() { return contactList == null? 0: contactList.size(); } // This method is called when binding the data to the views being created in RecyclerView @Override public void onBindViewHolder(@NonNull ContactHolder holder, final int position) { final Contact contact = contactList.get(position); // Set the data to the views here holder.setContactName(contact.getName()); holder.setContactNumber(contact.getNumber()); // You can set click listners to indvidual items in the viewholder here // make sure you pass down the listner or make the Data members of the viewHolder public } // This is your ViewHolder class that helps to populate data to the view public class ContactHolder extends RecyclerView.ViewHolder { private TextView txtName; private TextView txtNumber; public ContactHolder(View itemView) { super(itemView); txtName = itemView.findViewById(R.id.txt_name); txtNumber = itemView.findViewById(R.id.txt_number); } public void setContactName(String name) { txtName.setText(name); } public void setContactNumber(String number) { txtNumber.setText(number); } } }

Rigging up everything together in the Activity

It’s time we connect all of the dots together and feature our RecyclerView go up and strolling inside the hobby. Head back to the Activity Class and add the following matters to set it up. We need an example of RecyclerView and the Custom Adapter we just created, plus a list to preserve all the contact details. You can both hardcode the values of the touch or asynchronously load the data into the list and pass it right down to the adapter to do the activity of showing it in the RecyclerView.

public class MainActivity extends AppCompatActivity { private MyAdapter listAdapter; private ArrayList contactsList = new ArrayList<>(); private RecyclerView recycler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recycler = findViewById(R.id.recycler_view); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recycler.setLayoutManager(layoutManager); listAdapter = new MyAdapter(contactsList, this); recycler.setAdapter(listAdapter); //Load the date from the network or other resources //into the array list asynchronously contactsList.add(new Contact(“Daniel Shiffman”, “778899009”)); contactsList.add(new Contact(“Jhon Doe”, “778899009”)); contactsList.add(new Contact(“Jane Doe”, “778899009”)); listAdapter.notifyDataSetChanged(); } }

Creating Custom Recycler Adapter for Multiple Views

This is an frequently misunderstood idea which has a verity of various implementation to get the process performed. For a higher performance of the RecyclerView we ought to create an adapter with Multiple ViewHolder training. Often visible way is to use visibility to manipulate the perspectives inside a single view holder, that is vaguely incorrect manner of doing this. Let’s have a observe a RecyclerView Adapter which implements more than one views. What we want:

  • Multiple Layout template files for objects
  • POJO classeswith kind indicator variables if the statistics is hetrogenous
  • Multiple ViewHolders in the Adapter

Rest all of the implementation of the custom adapter is identical because the preceding one, except the Multiple view adapter’s magnificence and the POJO will appearance similar to the following.

public class Contact { //Add the type indicators here public static final int TEXT_TYPE = 0; public static final int IMAGE_TYPE = 0; private int viewType; private String name; private String number; public Contact(int viewType,String name, String number) { this.viewType = viewType; this.name = name; this.number = number; } public int getViewType() { return viewType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }

Adapter for Multiple Views

Note that we’re the use of a unique integer to note the form of view the item calls for inside the RecyclerView. This indicator can be used inside the RecyclerView Adapter to apply a selected layout with the ViewHolder. Here the Notable parts are the ViewType indicator variables within the statistics class (model class), the overding of getItemViewType() method and switching the layouts based in this on the onCreateViewHoder approach.

public class MyAdapter extends RecyclerView.Adapter { // List to store all the contact details private ArrayList contactsList; private Context mContext; // Counstructor for the Class public VideoListAdapter(ArrayList contactsList, Context context) { this.contactsList = contactsList; this.mContext = context; } // This method creates views for the RecyclerView by inflating the layout // Into the viewHolders which helps to display the items in the RecyclerView @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); // Inflate the layout view you have created for the list rows here // use the viewType to inflate specic Layouts for the ViewHolders switch(viewType) { case Contact.TEXT_TYPE: // Inflate the first view type View view = layoutInflater.inflate(R.layout.list_layout_1, parent, false); return new ViewHolder1(view); case Contact.TEXT_TYPE: // inflate the second view type View view = layoutInflater.inflate(R.layout.list_layout_2, parent, false); return new ViewHolder2(view); } // always use a fallback ViewHolder View view = layoutInflater.inflate(R.layout.default_list_layout, parent, false); return new ViewHolder(view); } @Override public int getItemCount() { return contactList == null? 0: contactList.size(); } @Override public int getItemViewType(int position) { int type = contactsList.get(position).getViewType(); return type; } // This method is called when binding the data to the views being created in RecyclerView @Override public void onBindViewHolder(@NonNull ContactHolder holder, final int position) { final Contact contact = contactList.get(position); // Set the data to the views here holder.setContactName(contact.getName()); holder.setContactNumber(contact.getNumber()); // You can set click listners to indvidual items in the viewholder here // make sure you pass down the listner or make the Data members of the viewHolder public } // This is your ViewHolder class that helps to populate data to the view public class viewHolder1 extends RecyclerView.ViewHolder { // Your First view holder // Connect with the items in the layout here } public class viewHolder2 extends RecyclerView.ViewHolder { // Your Second view holder // Connect with the items in the layout here } }