Wednesday, September 18, 2013

Android ListView with Speech Bubble

Hi,

Android Speech Bubble
example
Today I'm going to discuss how to make a ListView with speech bubble same as native android message app or some other apps out there. First of all we need to discuss the making of a row layout with speech bubble.

How to make Speech Bubble?

Well that is the most interesting part of the development. I've already posted a blog post about how to make 9 patch image of speech bubble, you can find that post here.


Here we will discuss how to use them in our application. You will copy them into your project in relevant hdpi, ldpi, xhdpi and mdpi folders accordingly. Now we come to the coding part.

We need to make simple ListActivity with ListView. There are lot of tutorials available:
and lot more. You can find customization of the ListView there too. Here I'll discuss the Adapter part of the ListView only.

What is Adapter in Android?

Android documentation says:
"An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set."

So an adapter is responsible to provide data, view as well as count of rows to AdapterView.

Good to remember: ListView, Gallery, GridView, ExpandableListView, Spinner etc are subclasses of AdapterView. So an adapter made for ListView can be used for other controls too and vice versa, with some minor modification.

We will customize the Adapter for that we need to have an xml layout and a java class extending BaseAdapter.

XML Layout for row

Here is the layout for the row:


In the above layout, we have defined a LinearLayout containing a TextView. We have set its background to one of the image we made as 9 patch (speech_bubble_green.9.png) and now we will use it in Adapter, so that we can use this layout in ListView.

Adapter for the ListView

Now we come to the java part and make an Adapter, here's how to customize the getView() method of the adapter to implement some sender and receiver side messages representation:

In the above code, we are first checking if the current message is ours ie. isMine() then we are aligning it to the right side and setting green background to it, and if its not ours then we are aligning the TextView to left side and setting orange background to it, that's all, we set this adapter to a ListView as traditional way and get a nice looking SMS messages ListView for android app.


Where to go now?  (Gimme Code)
Well you can find the full source code here. I've included the photoshop psd for the bubbles in relavent hdpi, ldpi, xhdpi and mdpi, if anyone want to edit them and use them for their project.

Suggestion and comments are welcome :)