简体   繁体   中英

listview item's background color changes on scrolling,

I have a listview , in which I am showing file and folder lists. I am using my getView method as

static class ViewHolder {
    protected TextView text1;
    protected TextView text2;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder = null;

    if(convertView == null){

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        
        convertView = inflater.inflate(R.layout.row, parent, false);

        viewHolder = new ViewHolder();
        viewHolder.text1 = (TextView) convertView.findViewById(R.id.text1);
        viewHolder.text2 = (TextView) convertView.findViewById(R.id.text2);

        convertView.setTag(viewHolder);

    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.text1.setText(itemsArrayList.get(position).getFileName());
    viewHolder.text2.setText(itemsArrayList.get(position).getSize());

    <if( itemsArrayList.get(position).isHidden() ) {
        convertView.setBackgroundColor(context.getResources().getColor(R.color.hiddenColor));
    }

    return convertView;
}

If file/folder is hidden , I am changing background color of list item as hiddenColor,
(default background color is in XML)

But on scrolling it sets almost all list item background color as hiddencolor.

I know this is due to listview recycling, but no idea how to resolve it.

You have to set the not hidden color too, because if the view is reused you will get the hiddenColor if it was set before to that convert view.

if( itemsArrayList.get(position).isHidden() ) {
    convertView.setBackgroundColor(context.getResources().getColor(R.color.hiddenColor));
} else {
   **convertView.setBackgroundColor(Put your other color here)**
}

在xml中放入android:fadingEdge="none"

尝试将其添加到xml文件中

android:cacheColorHint="@android:color/transparent"

You have to inflate layout for each item , and return a new view. Listview uses the same view for other items.

remove the if(convertView == null) , so that each item will have different view object .

Other way is to add the position in View holder , and check

 if(convertView == null || contentView.getTag().position != position)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM