Reputation: 136
i'm developing a WhatsApp like application with received messages aligned to the left e the sent messages aligned to the right.
How should I use ListView and Adapters to keep both received and sent messages in the same ListView?
Upvotes: 2
Views: 685
Reputation: 4028
You can manage it with a single Adapter
. What you need to look into are the Adapter's getItemViewType()
and getItemViewTypeCount()
methods.
The backing data for your adapter should contain both the sent and received messages with some sort of a flag to identify whether the message was a sent one or a received one.
Your getItemViewTypeCount()
should return 2 since you'll have two types of views - one of received chats and another for sent chats.
In your getView()
method, before inflating the views, check the getItemViewType()
for the position and inflate the right kind of view and set it up. You can even reuse the convertView. Android will take care of maintaining two pools of reusable views for you.
Upvotes: 0
Reputation: 649
If you want to use multiple adapters on the same listview you can use the jeff sharkey separated list adapter http://jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/ or you can overide getView in your custom adapter like edoardotognoni said.
Upvotes: 1
Reputation: 912
I think it's not possible you have a listview with two adapters but you can create an adapter, override the getView method and define an layout for each item and if the actual message is a received message, align left, and if it's a send message, align right.
Upvotes: 0
Reputation: 2752
I suggest you to create a Message class. This class has one boolean for example that is boolean sent;
So if it's true you know that it is sent from you.
When you create a custom adapter for the list view, you could do:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.rowcustom, null);
Message msg = getItem(position)
if (msg.isSent()) {
// Message is sent
}
else {
// Message is received
}
return convertView;
}
Upvotes: 2
Reputation: 8892
You don't need two adapters or listviews. Just use one adapter with a datastructure underlying and when you send a message or receive one, append the message to the list and it will show. Add a flag to the message class which says whether it is sent or received in which case the custom adapter can align the message correctly
Upvotes: 1