Search code examples
androidlistviewloaderandroid-cursoradapter

How to change the text color of certain TextViews in my ListView Cursor Adapter


I have a ListView cursor adapter loader. I want to change the text color of some TextViews in the ListView depending on a value in the cursor. The problem is that the CursorAdapter is recycling views so I get erroneous changes.

This is my Cursor Adapter

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {


        final LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(layout, parent, false);


        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor){
        TextView name_text = (TextView) view.findViewById(R.id.text1);
        String name = cursor.getString(cursor.getColumnIndex("name"));
        name_text.setText(name);
        // below is the problem...  the color change is being 
        // attributed to erroneous textviews in my list.
        if (cursor.getInt(cursor.getColumnIndex("favourite"))==1){
            name_text.setTextColor(Color.parseColor("#FFFFFF"));
        }
    }
}

this is my main

    int[] to = new int[] { R.id.text1 };
    String[] columns = new String[]{ "name" };
    dataAdapter = new CustomAdapter(this, R.layout.text_view, null, columns, to, Adapter.NO_SELECTION);
    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setAdapter(dataAdapter);
    listView.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view,
                int position, long id) {
            Intent intent = new Intent(getBaseContext(), Recipe.class);
            intent.putExtra("ca.ryanklemm.recipebook._id", (int)id);
            startActivity(intent);
        }
    }       );
    getSupportLoaderManager().initLoader(loaderID, null, this);

Solution

  • While dealing with views inside of adapters always use else with every if statement.

    if (cursor.getInt(cursor.getColumnIndex("favourite"))==1){
       name_text.setTextColor(Color.parseColor("#FFFFFF"));
    }else{
       name_text.setTextColor("Default Color");
    }