Search code examples
javaandroidlistviewcursorandroid-cursoradapter

CursorAdapter strange behaviour


In my app I show some info and depending on the value I change the color of the textView.

public class DealsAdapter extends CursorAdapter {
    private Cursor mCursor;
    private Context mContext;
    private final LayoutInflater mInflater;

    public DealsAdapter(Context context, Cursor cursor) {
        super(context, cursor, true);
        mInflater = LayoutInflater.from(context);
        mContext = context;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view = mInflater.inflate(R.layout.deals_row, parent, false);
        return view;
    }

    @Override
    public void bindView(View row, Context context, Cursor cursor) {
         Text View percent = (TextView) row.findViewById(R.id.tvPercent);
          percent.setText(cursor.getString(cursor
                .getColumnIndex(DBHelper.D_PERCENT)));
          float percentV = cursor.getFloat(cursor
                .getColumnIndex(DBHelper.D_PERCENT));
          if (percentV >= 41 && percentV <= 70) {
            // Orange
            percent.setTextColor(Color.parseColor("#F58549"));
        } else if (percentV >= 71) {
            // Green
            percent.setTextColor(Color.parseColor("#17D11D"));
        }
}

The problem is after i scroll up and down the colors start getting mixed up but the values stay the same.

Any advice?

Edit: In the xml I set the color to red and only change if needed.


Solution

  • You aren't explicitly setting a colour if percentV < 41. This means the item will retain whatever colour that view had previously, giving unpredictable results.

    This is because each item's View may be reused for performance reasons. If you scroll one item off the top of the screen, the same View may be used for the new item appearing at the bottom of the screen, to save the cost of inflating a new one each time. You have to explicitly set the default colour in bindView(), or else the View will retain whatever colour it had for the last item it contained.