This tutorial covers ‘Advanced’ custom listview concepts. The code is available on Github.
Android Hive provides an awesome tutorial on how to create a custom list view but you can still take things a notch higher and create a ListView like what Whatsapp or Telegram use. Their Lists allow you to click on either the contact or the profile picture.
By the end of it we will be able to click on an item on the list eg the image. Below is the final output.
Enough talk..let’s code.
Tools of Trade
- RecyclerView: Our list will extend RecyclerView instead of BaseAdapter. RecyclerView is more flexible that ListView and has a better perefomance. For more info check out https://developer.android.com/training/material/lists-cards.html
- Viewholder Pattern: This pattern consists of a simple class that holds the references to the UI components for each row in the ListView. This pattern avoids looking up the UI components all the time the system shows a row in the list.
Let’s get our hands dirty
1. We need to add RecyclerView dependency in our gradle file.
2. Creating a RecyclerView is very similar to the ListView.
3. In onCreate we setup the recyclerview.
4. Now create
Movie.java under model package. This model class will be used to provide movie objects data to listview after parsing the json.
5. Create a class named
ListAdapter.java with below code. This is a custom list adapter class which provides data to list view. In other words it renders the
movie_item_layout.xml in list by pre-filling appropriate information. This adapter must extend a class called
RecyclerView.Adapter passing our class that implements the ViewHolder pattern. We then to define our data model that stands at the base of our UI that implements the ViewHolder design pattern.
6. I created a method
onMemberClick() that handles onClick behavior when the add/remove button is clicked.
7. In the
MainActivity.java,I created volley’s JsonArrayRequest to get the json from url. Upon parsing the json, I stored all the json data into an ArrayList as Movie objects.
That is all folks. If you have any questions, comment below. If you have a better way of doing it, please, help me out.