Luca Vitucci
Luca Vitucci

Reputation: 3734

Android Performance issues with ViewHolder

I'm creating some ViewHolders for my projects's ListViews, inside the viewholders i'm storing the views, ImageViews, TextViews and more.

In the viewholder's class i created also methods to configure the views from the item's status, I.E:

For a chat message list item, i'll have a viewholder with a textview for the message's sender, an imageview with his avatar, an imageview that contains images from App's Resources to identify the message as an Audio Message, Video Message, Text Message and so on. In the same ViewHolder i've got also methods like:

configureViewFromMessage(MessageSender sender, Message message)

that configures the avatar, sender name and message type from Sender and Message POJO models.

EDIT: I'm adding an example Adapter to explain this better.

public View getView(int position, View convertView, ViewGroup viewGroup) {
    ContactViewHolder cvh;

    if (convertView != null) {
        cvh = (ContactViewHolder) convertView.getTag();
    } else {
        convertView = InflateUtils.inflate(mContext, R.layout.contact_list_item);
        convertView = InflateUtils.inflate(mContext, R.layout.contact_list_item_container);
        cvh = new ContactViewHolder(innerView);
        convertView.setTag(cvh);
    }

    /* Getting message */
    Message message = getItem(position);
    MessageSender sender = message.getSender();

    /* View settings */
    cvh.configureViewFromMessage(sender, message, mContext);
        /* Context is used to reach App's Resources */

    return convertView;
}

Questions are:

  1. Having those methods (possibly many) inside a ViewHolder can cause performance issues?
  2. Should i keep in the ViewHolders only the strictly required fields and no methods?

Upvotes: 0

Views: 167

Answers (1)

Jilberta
Jilberta

Reputation: 2866

As you know, ViewHolder is used to optimize ListView-s performance like saving already created view and after scrolling you're taking this view, change its image or text or whatever view you have and put it back as another ListItem. So you avoid using findViewById() and creating new views everytime.

In my opinion, if you put some methods in ViewHolder it shouldn't cause any performance issues to ListViews, unless those methods are badly written. As long as you're avoiding creating new views and using findViewById() everytime it should be ok.

Upvotes: 2

Related Questions