Android,使用SimpleCursorAdapter设置颜色而不仅仅是字符串

Ham*_*mid 8 android listview simplecursoradapter

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

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});
Run Code Online (Sandbox Code Playgroud)

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

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

Mat*_*lis 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);
Run Code Online (Sandbox Code Playgroud)

更新 - 如果您使用自定义适配器(扩展CursorAdaptor),那么代码不会改变很多.你会压倒一切,getView并且bindView:

@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);
}
Run Code Online (Sandbox Code Playgroud)

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