如何更改ListView光标适配器中某些TextView的文本颜色

时间:2015-07-07 06:50:20

标签: android listview loader android-cursoradapter

我有一个ListView游标适配器加载器。我想根据光标中的值更改TextViews中某些ListView的文本颜色。问题是CursorAdapter是回收视图,因此我得到了错误的更改。

这是我的光标适配器

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

这是我的主要

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

1 个答案:

答案 0 :(得分:2)

在处理适配器内部的视图时,始终对每个else语句使用if

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