如何更改 ListView 中元素的背景颜色(来自 ContentProvider 的数据)?

How to change background color of elements in ListView(data from ContentProvider)?

我需要根据元素的状态更改 ListView 中元素的背景颜色。 lvLinks.getCount() returns 正确的值。 "If-else" 并且日志也可以正常工作。但它不起作用(不改变背景颜色)。请帮我!希望你能理解我的代码。

final Uri CONTACT_URI = Uri.parse("content://com.application.provider.LinkProvider/links");
ListView lvLinks;
Cursor cursor;
SimpleCursorAdapter adapter;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);

    lvLinks = (ListView) findViewById(R.id.lvLinks);
    showListView(null);
    setBackgroundColor();
    lvLinks.setOnItemClickListener(this);
}


public void showListView(String order){
    cursor = getContentResolver().query(CONTACT_URI, null, null,
            null, order);
    startManagingCursor(cursor);

    int to[] = { android.R.id.text1, android.R.id.text2 };
    String from[] = {"ref" , "status"};
    adapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_2, cursor, from, to);
    lvLinks.setAdapter(adapter);


}

public void setBackgroundColor(){


    for(int i = 0; i < lvLinks.getCount(); i++){
        View v = lvLinks.getAdapter().getView(i, null, null);
        Cursor cursor = (Cursor) lvLinks.getItemAtPosition(i);
        int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
        Log.d("MYTAG", String.valueOf(status));
        if (status == 1){
            v.setBackgroundColor(Color.GREEN);
            Log.d("MYTAG", "GREEN");
        } else if (status == 2){
            v.setBackgroundColor(Color.RED);
            Log.d("MYTAG", "RED");
        } else if (status == 3){
            v.setBackgroundColor(Color.GRAY);
            Log.d("MYTAG", "GRAY");
        }
    }
}

首先:当您将联系人数据绑定到该行时,您的适配器应该处理设置视图的背景颜色。 SimpleCursorAdapter 没有这样做的逻辑。您应该扩展 CursorAdapter 并实施 bindView() 以按照您想要的方式处理此问题。

其次:startManagingCursor() 已弃用。学习使用 Loader 框架,特别是 CursorLoader.