使用SimpleCursorAdapter.ViewBinder改变TextView的颜色

2023-12-05

我正在为 Android 开发一个闹钟应用程序,我想在主屏幕上显示闹钟列表。这个的每一行ListView是在xml文件中定义的。我想要单独的TextViews一周中的每一天。程序将检查 sqlite 数据库,例如。价值mondayis = 1 然后改变它的颜色TextView为红色。我已经写了这段代码,但是不起作用。怎么了?

private void fillData() {

    // Get all of the notes from the database and create the item list
    Cursor c = db.fetchAllAlarms();
    startManagingCursor(c);

    String[] from = new String[] { db.KEY_TIME, db.KEY_NAME };
    int[] to = new int[] { R.id.time, R.id.alarmName };

    // Now create an array adapter and set it to display using our row
    SimpleCursorAdapter alarms =
        new SimpleCursorAdapter(this, R.layout.alarm_row, c, from, to);
        alarms.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            int dayOfWeekIndex = cursor.getColumnIndex("mon");
            if (dayOfWeekIndex == columnIndex) {
                int color = cursor.getInt(dayOfWeekIndex);
                switch(color) {
                case 0: ((TextView) view).setTextColor(Color.RED); break;
                case 1: ((TextView) view).setTextColor(Color.GRAY); break;
                }
                return true;
            }
            return false;
        }
    });

来自 Android 文档SimpleCursorAdapter.ViewBinder:

将指定索引定义的 Cursor 列绑定到 指定视图。当绑定由该 ViewBinder 处理时, 方法必须返回 true。如果此方法返回 false, SimpleCursorAdapter 将尝试自行处理绑定。

换句话说,您的实施setViewValue不应该具体针对任何一个人View, as SimpleCursorAdapter将对每个进行更改View(根据您的实现)当它填充时ListView. setViewValue基本上你有机会用你的数据做任何你想做的事Cursor,包括设置视图的颜色。尝试这样的事情,

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

请注意,上面的代码假设有一个名为"day_of_week"其中持有一个int值 0-6(指定一周中的特定日期)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用SimpleCursorAdapter.ViewBinder改变TextView的颜色 的相关文章

随机推荐