简体   繁体   中英

Change background color of ListView item after 3 seconds

I have a list of Items that are "seen" or "not seen" in ArrayList<Item> . If they're not seen I change the background color of the ListView item in my CustomArrayAdapter like this :

 if(item.is_seen == null || item.is_seen == 0) {
    row.setBackgroundResource(R.color.yellow);
 } else {
    row.setBackgroundResource(R.color.transparent);
 }

Now what I want to do is set all items background to transparent after 3 seconds spent on the page.

I already tried to do something like this:

mScheduledExecutor.schedule(new Runnable() {
@Override
public void run() {


for(int i=0; i<mItems.size(); i++) {
    final Item n = mItems.get(i);
    if(n.is_seen == null || n.is_seen == 0) {

        // update value in db
        int isSeen = 1;
        updateItem(n._id, isSeen);

        // change the color of backgrounds
        View view = listViewItem.getChildAt(i);
        if(view != null) {
            view.setBackgroundResource(R.color.red);
        } 
      }
}

Updating the value in the DB works, but the rest doesn't. But I'd like to avoid to reload the data. I just need the color to change.

I don't have errors, it just does nothing.

I look everywhere for an answer and didn't find one. Am I wrong since the beginning? Is what I want to achieve even possible?

I thank you in advance for all the help you could give me.

Instead of changing the color of the view like youre doing,

// change the color of backgrounds
        View view = listViewItem.getChildAt(i);
        if(view != null) {
            view.setBackgroundResource(R.color.red);
        } 

(code above will not work, because the views are recycled in the ListAdapter) update the DATA off which you build your list - add a property to the class you are passing into your ListAdapter, then grab that instance from the list and update that property, you have the position at which it needs to be updated already, so that's easy. Then, call notifyDataSetChanged() on the list. It will not redraw the list if you didn't ADD/REMOVE items from list, but it will update correct view for you. This is the only way to do it - absolutely NO WAY to get to a view corresponding to a specific element in a list after list has been drawn already. Only way is to refresh/redraw the list with notifyDataSetChanged(), followed by refreshDrawableState().

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