8

我在应用程序的列表中设置了一个简单的光标适配器,如下所示:

private static final String fields[] = {"GenreLabel", "Colour", BaseColumns._ID};


datasource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[]{R.id.genreBox, R.id.colourBox});

R.layout.row 由两个 TextViews(genreBox 和 colourBox)组成。我不想将 TextView 的内容设置为 "Colour" 的值,而是将其背景颜色设置为该值。

我需要做些什么来实现这一目标?

4

2 回答 2

13

查看SimpleCursorAdapter.ViewBinder

setViewValue基本上是你对你的数据做任何你想做的事情的机会Cursor,包括设置你的视图的背景颜色。

例如,类似:

SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        String name = cursor.getColumnName(columnIndex);
        if ("Colour".equals(name)) {
            int color = cursor.getInt(columnIndex);
            view.setBackgroundColor(color);
            return true;
        }
        return false;
    }
}
datasource.setViewBinder(binder);

更新- 如果您使用的是自定义适配器(扩展CursorAdaptor),那么代码不会发生很大变化。你会覆盖getViewbindView

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView != null) {
        return convertView;
    }
    /* context is the outer activity or a context saved in the constructor */
    return LayoutInflater.from(context).inflate(R.id.my_row);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    int color = cursor.getInt(cursor.getColumnIndex("Colour"));
    view.setBackgroundColor(color);
    String label = cursor.getString(cursor.getColumnIndex("GenreLabel"));
    TextView text = (TextView) findViewById(R.id.genre_label);
    text.setText(label);
}

你手动做的更多,但它或多或少是相同的想法。请注意,在所有这些示例中,您可以通过缓存列索引而不是通过字符串查找它们来节省性能。

于 2011-04-06T22:12:39.920 回答
0

您要查找的内容需要自定义光标适配器。您可以继承 SimpleCursorAdapter。这基本上可以访问创建的视图(尽管您将自己创建它)。

有关完整示例,请参阅有关自定义 CursorAdapters 的此博客文章。特别是,我认为您需要覆盖bindView.

于 2011-04-06T22:17:34.263 回答