Search code examples
androidlistadapter

Display different objects in the same ListAdapter


I would like to display different types of objects in the same ListView, but I don't know how to differentiate these Objects via getItem(position)

The ListView displays a list of Messages which can be either a Chat, either a Notification, and the items Chat and Notification have different layout.

This is the adapter :

public class MailboxAdapter extends BaseAdapter {

    private ArrayList<Messages> m_alMessages = null;

    private Messages getItem(int position) {

        return m_alMessages.get(position)
    }

   @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (m_alMessages != null) {
            if (getItem(position).isChat()) {
                final Chat cChatItem = getItem(position);
                if (convertView == null) {
                    //Cat logic
                    // ...
                }
            } else {
                final Notification nNotifItem = getItem(position);

                 if (convertView == null) {
                    //Notification logic
                    // ...
                }

            }
        }
    }

the Message Class (minimal)

public class Message {
        private long m_lId = 0L;
        private boolean m_bIsChat = false;

        public boolean isChat() { return m_bIsChat; }

}

the Notification and Chat classes :

public class Notification extends Message { ... }

public class Cat extends Message { ... }

I am retrieving a list of Chats and a List of Notifications from web-services when starting the activity, so I would have to add them to a new list of Messages in their respective order (date), and then instantiate m adapter with this list of Message

Is it a good practice ?


Solution

  • Just add a boolean flag to the class object and in the adapter, check the flag and use one layout if its a chat, another if it is flagged as a notification. No problem with that

    There is a tutorial here which actually covers more or less what you are trying to do with different view layouts within a listView

    Within your adapter create two viewholders, one for chat, one for notification. Then, in getView(), get the object which you are creating the view for, check the boolean flag, instantiate the correct holder and inflate the view based upon the flag and then set the view elements as you would if there was just that one class and the ListView will show the view you set up that element in place.