Doug Conran
Doug Conran

Reputation: 459

Change the background of an item in a ListView displayed

I have a ListView populated from a database using a customized ResourceCursorAdapter with a bindView to format each list item. The items are displayed in descending chronological order and I need to hightlight the first future event. Unfortunately I only know that it is the first future event when I process the next entry and find that it is in the past. What I really need is the ability to 'look ahead' in the bindView processing but that is not there.

The only alternative (that I can think of) is to process all items and then go back to change the background of the first future event (which I would then know).

The code I'm using is

    EventsAdapter db = new EventsAdapter(this);
    db.open();

    Cursor cursor = db.fetchAllRecords();

    final MyAdapter listitems = new MyAdapter(this,R.layout.timeline_detail, cursor, 0);
    timeline.setAdapter(listitems);

    db.close();

    View v = timeline.getChildAt(firstEvent);  // firstevent is set in the bindView
    v.setBackgroundColor(Color.parseColor("#ffd1d1"));

However the View v is always null and, when I run it in debug mode with a breakpoint at the View statement, the listview has not yet rendered on the screen. I'm assuming, therefore, that that is why the view is still null.

How can I get and changeView the ListView item that needs to be changed at the time that the ListView is first displayed?

Upvotes: 0

Views: 46

Answers (1)

Andrei Tudor Diaconu
Andrei Tudor Diaconu

Reputation: 2247

Try and extend your adapter and override getView.

final MyAdapter listitems = new MyAdapter(this,R.layout.timeline_detail, cursor, 0){
    public View getView(int position, View convertView, ViewGroup parent){
        View v = super.getView(position, convertView, parent);
        if (position==0){
            //Do something to the first item (v)
        }else{
            //Revert what you did above, since views get recycled.
        }
        return v;
    }
};

or just include that in your MyAdapter class.

Upvotes: 1

Related Questions