Android using SimpleCursorAdapter to set color not only strings

I have a simple cursor adapter installed in a list in my application, as follows:

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 consists of two TextViews (genreBox and colourBox). Instead of setting the contents of the TextView to "Color", I would like to set its background color to this value.

What do I need to do to achieve this?

+8
android listview simplecursoradapter
source share
2 answers

Check out SimpleCursorAdapter.ViewBinder .

setViewValue is basically your chance to do whatever you want with the data in Cursor , including adjusting 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 use a custom adapter ( CursorAdaptor extension), then the code will not change completely. You would override 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 do a little more by hand, but this is more or less the same idea. Note that in all of these examples, you can save on performance by caching column indices rather than looking through them row by row.

+13
source share

For your search you need a custom cursor adapter. You can subclass SimpleCursorAdapter . This basically gives access to the view as it was created (although you yourself will create it).

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

0
source share

All Articles