Using SimpleCursorAdapter.ViewBinder to change the color of TextView

前端 未结 2 1995
猫巷女王i
猫巷女王i 2021-01-06 11:27

I\'m developing an alarm clock app for android and I want to have displayed list of alarms on the main screen. Each row of this ListView is defined in xml file.

2条回答
  •  没有蜡笔的小新
    2021-01-06 12:06

    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).

提交回复
热议问题