Saturday, April 30, 2016

Tutorial: Android ListView With Custom Adapter

There are so many apps utilizing ListView in Android. Your feed in a social network, your tasks in a to-do app, even your mail in your favorite email app stored in a ListView.


Basically, ListView is a container for a collection of items that can be represented as an array. You should be able to get any item from a collection by its index and get the size of an underlying collection. Also, it would be nice to be able to add new elements to your collection unless you want it to be constant.

In my opinion, ArrayList fits this definition perfectly. In ArrayAdapter, they use List as an underlying collection, though, but in some implementations of it (LinkedList for example) get operation is linear of index you pass to it, so it can be bad for performance. But it's not a reason to reject ArrayAdapter, just be careful with what implementation you pass to it.

Custom List Adapter

ArrayAdapter by default adapts only strings to TextViews, but we want something more interesting.

Let's say we are developing a messaging app and we want to show active conversations. We will represent our chat with this class.

public class Chat {
    private int mProfilePic;
    private String mName;
    private String mMessage;

    Chat(int profilePic, String name, String message) {
        mProfilePic = profilePic;
        mName = name;
        mMessage = message;
    }

    public int getProfilePic() {
        return mProfilePic;
    }

    public String getName() {
        return mName;
    }

    public String getMessage() {
        return mMessage;
    }
}


So we want our ListView to show some information besides strings. How do we do that?

Turns out it's not so complex if you know the basics!

There are several ways to achieve this goal. One of these is to use ArrayAdapter and override getView method (the simplest) and the other is to build your WhateverYouWantAdapter that will extend BaseAdapter class (the funniest).

Let's consider both approaches.

ArrayAdapter

There is a method getView in all adapters that returns the view of your list item.

By default ArrayAdapter just finds TextView passed as a parameter to its constructor and sets the text that is stored in underlying list (by the way if your objects are not Strings it just calls toString and makes them so). You can find this in source code (line 368 see createViewFromResource method).

So to implement custom ListView we just need to override this behavior. But wait a minute you also need some place to put your data in right. Let's build a simple layout that will represent our conversation.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">
    <!--I'm using hdodenhof's library to make image circle-->
    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_pic_imageview"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:scaleType="centerCrop"
        android:layout_marginEnd="8dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            android:layout_marginBottom="12dp"/>
        <TextView
            android:id="@+id/message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"/>
    </LinearLayout>
</LinearLayout>

Where is Harry?

So here we have our friend's profile pic, his name and last message received from him.

In our getView method, we need to get access to them and set values.

public class ChatAdapter extends ArrayAdapter<Chat> {

    public ChatAdapter(Context context, int resource, ArrayList<Chat> data) {
        super(context, resource, data);
    }

    public View getView(int position, View view, ViewGroup parent) {
        //Get the instance of our chat
        Chat chat = getItem(position);

        LayoutInflater inflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE );

        //Create new list item
        View rowView = inflater.inflate(R.layout.list_item, null, true);

        //Get UI objects
        ImageView profilePic = (ImageView) rowView.findViewById(R.id.profile_pic_imageview);
        TextView nameView = (TextView) rowView.findViewById(R.id.name);
        TextView messageView = (TextView) rowView.findViewById(R.id.message);

        //Set image profile picture
        profilePic.setImageDrawable(getContext().getResources().getDrawable(chat.getProfilePic()));

        //Set text into TextViews
        nameView.setText(chat.getName());
        messageView.setText(chat.getMessage());

        return rowView;
    }

}


After that just make some test data and set your adapter to the list, everything else will be handled by Android.

ArrayList<Chat> chats = new ArrayList<>();
chats.add(new Chat(R.drawable.hermione, "Hermione Granger", "Harry! Where are you? " +
                "Dambledore is looking for..."));
chats.add(new Chat(R.drawable.ginger, "Ron Weasley", "Wingardium leviosaaaaaaaaaaaaaaaa"));
chats.add(new Chat(R.drawable.snape, "Severus Snape", "Well, it may have escaped your " +
                "notice, but life is not ..."));
chats.add(new Chat(R.drawable.iman, "Tony Stark", "I don't know why I'm even chatting with you"));

ChatAdapter adapter = new ChatAdapter(this, R.id.listview_chats, chats);

ListView chatList = (ListView) findViewById(R.id.listview_chats);
chatList.setAdapter(adapter);

BaseAdapter

This approach is manual but it's also fun because you will build your very own adapter and will understand deeply how adapters work.

The main idea is the same to override some methods in BaseAdapter they are not even implemented, so, we will do it manually. Also in the BaseList, there is no any underlying collection to store data, it means we need to make out own.

Let's use the same layout for list items. For our adapter to work we need to implement getView, getItem, getItemId, getCount methods. But before diving in the code let's consider what these should do.

  • getView(int position, View view, ViewGroup parent): for the getView idea is the same as for ArrayAdapter it should return our list item layout.
  • getItem(int pos): this method should return an instance of the object we store in list item in pos position. 
  • getItemId(int pos): you need this when for example when you use a database to retrieve items for your list, it just makes it easier to get item's id in this database. We need to implement to make our adapter work, let's just return 0 from it.
  • getCount(): this method just returns number of elements in your list

public class ChatAdapter extends BaseAdapter {
    private final Activity mContext;
    private final ArrayList<Chat> mChats;
    private final Resources mRes;
    private final LayoutInflater mInflater;

    public ChatAdapter(Activity context, ArrayList<Chat> chats) {
        mContext = context;
        mChats = chats;
        mRes = mContext.getResources();
        mInflater = mContext.getLayoutInflater();
    }

    @Override
    public int getCount() {
        return mChats.size();
    }

    @Override
    public Chat getItem(int pos) {
        return mChats.get(pos);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View view, ViewGroup parent) {
        //Get the instance of our chat
        Chat chat = mChats.get(position);

        //Create new list item
        View rowView = mInflater.inflate(R.layout.list_item, null, true);

        //Get UI objects
        ImageView profilePic = (ImageView) rowView.findViewById(R.id.profile_pic_imageview);
        TextView nameView = (TextView) rowView.findViewById(R.id.name);
        TextView messageView = (TextView) rowView.findViewById(R.id.message);

        //Set image profile picture
        profilePic.setImageDrawable(mRes.getDrawable(chat.getProfilePic()));

        //Set text into TextViews
        nameView.setText(chat.getName());
        messageView.setText(chat.getMessage());

        return rowView;
    }

}

And now you can use you newborn adapter just as ArrayAdapter

There is a little bit different constructor so you should change one line of code just write
ChatAdapter adapter = new ChatAdapter(this, chats);
Instead of
ChatAdapter adapter = new ChatAdapter(this, R.id.listview_chats, chats);

Result

Stop! Tony Stark???
Both approaches led me to this view. It's pretty much it. I think we've got nice cosy layout and our users will be satisfied :)

Summary

Of course, it's better to use an ArrayAdapter but I didn't include BaseAdapter part "just because". I think it will deepen your understanding of how does ListAdapter works and will encourage you to learn how things work internally in Android.

Now I'm looking forward to writing more tutorials, so stay tuned. See you next week, peace!

P.S. You can look at my code on my GitHub repository

4 comments:

  1. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.Android Training in chennai |Android Training in Velachery

    ReplyDelete
  2. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.android development course fees in chennai | android app development training in chennai

    ReplyDelete
  3. It's really interesting I'll be read that many of the bloggers relevant android development that's time I read that's your tips helped me and clarify the new thing.We share this tutorial for android ListView Custom method is excellent.I really appreciate to tutorial.
    example:







    Selenium Training in Chennai | Selenium Testing Training in Chennai | Best Hadoop Training in Chennai | Android Training in Chennai with placement

    ReplyDelete
  4. It's really interesting I'll be read that many of the bloggers relevant android development that's time I read that's your tips helped me and clarify the new thing.We share this tutorial for android ListView Custom method is excellent.I really appreciate to tutorial.
    example:







    Selenium Training in Chennai | Selenium Testing Training in Chennai | Best Hadoop Training in Chennai | Android Training in Chennai with placement

    ReplyDelete