【问题标题】:How to change the text color of certain TextViews in my ListView Cursor Adapter如何在我的 ListView 光标适配器中更改某些 TextViews 的文本颜色
【发布时间】:2015-07-07 06:50:20
【问题描述】:

我有一个ListView 光标适配器加载器。我想根据光标中的值更改ListView 中某些TextViews 的文本颜色。问题是 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);

【问题讨论】:

    标签: android listview loader android-cursoradapter


    【解决方案1】:

    在处理适配器内部的视图时,总是在每个 if 语句中使用 else

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

    【讨论】:

    • 我很抱歉。它解决了我的问题。除了良好的编程习惯,为什么我还需要 else 语句?
    • 如您所说,它会返回回收的视图。因此,回收视图可以是您更改为默认视图颜色的最后更新视图。
    猜你喜欢
    • 2015-07-12
    • 2012-05-01
    • 2019-10-01
    • 2012-12-26
    • 1970-01-01
    • 2011-09-07
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多