One of the most interesting things using this Base Adapter is that you can implement a list of everything you need. Le'ts use an example. Imagine that we are working in a Twitter application. Our application has a list of tweets, with the avatar, the name of the user, the tweet itself etc... so, lets suppose we have a class “Tweet”, this class “Tweet” then has the following fields:
String tweet
String userName
Date tweetSend
Bitmap imageAvatar
So, this is the information we want to show in every row in the list.
Lets compose our main Activity.
Here we have:
List<Tweet> tweetList;
(We fill this list from a database we have, from information in the Internet, etc...)
In our Activity (We are using a Activity not a ListActivity!!) we get the “listview” element we should have in our XML. (Remember, every Activity has an XML file associated with it)
Then, we have to call this method:
TweetRowAdapter adapter = new TweetRowAdapter(this, tweetList);
(The list must be fill with data!!)
The TweeetRowAdapter class is a class created by ourselves, this class extends BaseAdapter:
public class TweeetRowAdapter extends BaseAdapter {
This class have some methods that have to be implemented:
public int getCount()
public Object getItem(int position)
public long getItemId(int position)
And the MOST important:
public View getView(int position, View convertView, ViewGroup parent)
The way to implement the 3 first methods is almost the same in all BaseAdapters:
public int getCount() {
return elements.size();
}
public Object getItem(int position) {
return elements.get(position);
}
public long getItemId(int position) {
return position;
}
Not very complex.
We need to create a constructor to call it from outside, passing a List of Tweets as parameters.
private List<Tweets> elements;
public TweeetRowAdapter(Context mContext, List<Tweet> elements) {
this.mContext = mContext;
this.elements = elements;
}
Now we have the list of tweets inside the Base Adapter. Now let's continue creating a custom View.