简体   繁体   中英

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.

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);
}

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);
    }
}

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