Ken Smith
Ken Smith

Reputation: 17

Setting background color for list item

I have a ListActivity that sets a SimpleCursorAdapter to a ListView in my XML file (android:id="@android:id/android:list"). I have five rows in a prefilled database. When the activity begins, I want to set the background of the list item view corresponding to the database row with _id 3 to Blue. This item can appear anywhere in the list because the user can add, edit and delete list items. (So I can't rely on indexing by child node number.) If the item was deleted, then I don't want to do anything.

How do I find the correct View?

Added info: The list item is organized like so (fyi, this is an outline, not the actual XML code):

<LinearLayout>
    <TextView/>
    <TextView/>
</LinearLayout>

That's the outline of the layout file that I pass to the SimpleCursorAdapter constructor.

Upvotes: 0

Views: 346

Answers (2)

Dan S
Dan S

Reputation: 9189

To expand on JoeLallouz's answer its actually the view's parent that needs to be changed (only once), plus we need some insight on the list item's layout.

public void bindView(View view, Context ctx, Cursor cursor) {
    if(view.getId() == R.id.known_view && cursor.getInt(cursor.getColumnIndex("_id"))==3) {
        // Works if view's parent is the root of the list item's layout
        ((View)view.getParent()).setBackgroundResource(R.drawable.my_blue_background);
    }
}

Upvotes: 0

JoeLallouz
JoeLallouz

Reputation: 1350

in the bindView() method of your adapter, you can determine the _id of the row and call view.setBackgroundResource(R.drawable.my_blue_background); would look something like this

public void bindView(View view, Context ctx, Cursor cursor) {
    if(cursor.getInt(cursor.getColumnIndex("_id"))==3)
        view.setBackgroundResource(R.drawable.my_blue_background);
}

Upvotes: 1

Related Questions