How to set background color through SimpleCursorAdapter

543 views Asked by At

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.stack.imgur.com/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.stack.imgur.com/wrXt8.jpg

Is that possible? Thanks.

2

There are 2 answers

0
alijandro On BEST ANSWER

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

}
0
Yuta73 On

There's no need to create a new class. See this code.

@Override
public boolean setViewValue(View view, Cursor c, int columnIndex) {
    if(columnIndex == c.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)) {
        TextView tv = (TextView)view;
        tv.setColor(Color.RED);
    }
}