androidlistviewsimplecursoradapter

How to set background color through SimpleCursorAdapter


Here is my code:

private void fillData() {
        Cursor notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);

        String[] from = new String[]{NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_COLOR};

        int[] to = new int[]{R.id.text1, R.id.text2};

        SimpleCursorAdapter notes = new SimpleCursorAdapter(
              this, R.layout.note_row, notesCursor, from, to);
        setListAdapter(notes);
        }

Which produces the following ListView: https://i.sstatic.net/7W1xa.jpg

What I want is to take "R.id.text2" value (which is a hex color) and set it as text color of itself, for each different row of my ListView.

The result should look like this: https://i.sstatic.net/wrXt8.jpg

Is that possible? Thanks.


Solution

  • Yes, it's possible. Create your own cursor adapter MyCursorAdapter which extend SimpleCursorAdapter, then override newView or bindView method.

    public class MyCursorAdapter extends SimpleCursorAdapter {
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }
    
    public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }
    
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        TextView textView = (TextView) view.findViewById(R.id.text2);
        String color = cursor.getString(cursor.getColumnIndex(NotesDbAdapter.KEY_COLOR));
        textView.setBackgroundColor(Color.parseColor(color));
    }
    
    }