Using SimpleCursorAdapter.ViewBinder to change the color of TextView

☆樱花仙子☆ 提交于 2019-12-01 00:03:52

From the Android documentation on SimpleCursorAdapter.ViewBinder:

Binds the Cursor column defined by the specified index to the specified view. When binding is handled by this ViewBinder, this method must return true. If this method returns false, SimpleCursorAdapter will attempts to handle the binding on its own.

In other words, your implementation of setViewValue should not be specific to any one View, as SimpleCursorAdapter will make changes to each View (according to your implementation) when it populates the ListView. setViewValue is basically your chance to do whatever you wish with the data in your Cursor, including setting the color of your views. Try something like this,

public boolean setViewValue(View view, Cursor cursor, int columnIndex){    
    // if this holds true, then you know that you are currently binding text to
    // the TextView with id "R.id.alarmName"
    if (view.getId() == R.id.alarmName) {
        final int dayOfWeekIndex = cursor.getColumnIndex("day_of_week");
        final int color = cursor.getInt(dayOfWeekIndex);

        switch(color) {
        case 0: ((TextView) view).setTextColor(Color.RED); break;
        case 1: /* ... */ break;
        case 2: /* ... */ break;
        /* etc. */
        }
        return true;
    }
    return false;
}

Note that the above code assumes a column named "day_of_week" which holds an int value 0-6 (to specify the specific day of the week).

From the Android documentation on SimpleCursorAdapter.ViewBinder:

Binds the Cursor column defined by the specified index to the specified view. When binding is handled by this ViewBinder, this method must return true. If this method returns false, SimpleCursorAdapter will attempts to handle the binding on its own.

In other words, your implementation of setViewValue should not be specific to any one View, as SimpleCursorAdapter will make changes to each View (according to your implementation) when it populates the ListView. Your implementation should look something like this,

notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        int dayOfWeekIndex = cursor.getColumnIndex("day_of_week");
        if (dayOfWeekIndex == columnIndex) {
            int color = cursor.getInt(dayOfWeekIndex);
            switch(color) {
            case 0: ((TextView) view).setTextColor(Color.RED); break;
            case 1: /* ... */ break;
            case 2: /* ... */ break;
            /* etc. */
            }
            return true;
        }
        return false;
    }
});

Note that the above code assumes a column named "day_of_week" which holds an int value 0-6 (to specify the specific day of the week).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!