ListView item coloring on selection not working properly in android API version 8/9

泄露秘密 提交于 2019-12-03 17:06:26

Wow, the problem was in my own implementation of ArrayAdapter, where I tried to apply view holder pattern. I discarded this initially because I tested the same with a simple ArrayAdapter and problem was still there.

The difference between android APIs is that when item is clicked in the 8-10 API, all list is repainted, reusing existing views. Therefore, when you click in a item (View), this is colored but immediatly android repaints all list, reusing the views, and making the colored one to be in other position. When a list view item gets clicked in >11 API, anything gets repainted (yes, great performance improvement between versions) and the correct item view was painted succesfully (calling properly view.setBackgroundColor(checkedColor)).

Finally, I solved this strange behaviour, storing checked state in the entities. With this, when the view has to be recycled, checked value can be recovered and list item can be colored without problems.

I post my GenericListAdapter.getView() method and related for anyone interested.

GenericListAdapter<T>.getView():

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ItemViewHolder<T> viewHolder = null;

    if (convertView == null || !(convertView.getTag() instanceof ItemViewHolder<?>)) {
        logger.debug("New view: " + convertView + " at position: " + position);
        LayoutInflater mInflater = LayoutInflater.from(context);
        convertView = mInflater.inflate(resource, null);

        viewHolder = GenericViewHolderFactory.createInstance(clazz);
        viewHolder.setContext(context);
        viewHolder.saveViewContents(convertView);

        convertView.setTag(viewHolder);
    } else {
        logger.debug("Reusing view: " + convertView + ", at position: " + position);
        viewHolder = (ItemViewHolder<T>) convertView.getTag();
    }

    T entity = getItem(position);
    viewHolder.setViewFields(entity, convertView);

    return convertView;
}

And the ViewHolder implementation which refreshes the recycled view:

public class EventItemViewHolder implements ItemViewHolder<Event> {

...

    @Override
    public void setViewFields(Event event, View convertView) {
        name.setText(event.getName());
        amount.setText(event.getTotalAmount().toString());

        if (event.isChecked()) {
            convertView.setBackgroundColor(checkedColor);
        } else {
            convertView.setBackgroundColor(uncheckedColor);
        }
    }
}

I hope I've explained myself well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!