Android, using SimpleCursorAdapter to set colour not just strings

六眼飞鱼酱① 提交于 2019-11-27 23:08:02

Check out SimpleCursorAdapter.ViewBinder.

setViewValue is basically your chance to do whatever you wish with the data in your Cursor, including setting the background color of your views.

For example, something like:

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

Update - if you're using a custom adapter (extending CursorAdaptor) then the code doesn't change a whole lot. You'd be overriding getView and 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);
}

You're doing a bit more manually, but it's more or less the same idea. Note that in all of these examples you might save on performance by caching the column indices instead of looking them up via strings.

What you're looking for requires a custom cursor adapter. You can subclass SimpleCursorAdapter. This basically give access to the view as its created (although you'll be creating it yourself).

See this blog post on custom CursorAdapters for a complete example. Particularly, I think you'll need to override bindView.

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