如何在CustomAdapter上动态更改单个TextView颜色?

时间:2018-04-11 08:41:50

标签: java android

我有一个CustomAdapter,我正在尝试根据写作类型改变颜色。

E.g。

如果字符串“categoria_label”将等于“apple”我想在textview上设置一个红色背景颜色,如果它是“菠萝”我想要设置黄色背景并继续...这对于CustomAdapter的每一行< / p>

我已经看过一个教程的赃物,我知道在CustomAdapter的getView()函数中可以修改单行

在Object PastChallenge中,有一个getter和一个setter来检索我的颜色。

public String getColore_categoria() {
    return colore_categoria;
}

public String setColore_categoria(String colore_categoria) {
    this.colore_categoria = colore_categoria;
    return colore_categoria;
}

但我不知道如何在CustomAdapter中更改它

也许我需要做一个案子?

CustomAdapter代码

public class PastChallengeAdapter extends ArrayAdapter<PastChallenge> {
    ArrayList<PastChallenge> PastChallengeList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public PastChallengeAdapter(Context context, int resource, ArrayList<PastChallenge> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        PastChallengeList = objects;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.Categoria = (TextView) v.findViewById(R.id.Categoria);
            holder.FirstUserName= (TextView) v.findViewById(R.id.FirstUserName);
            holder.secondUserName = (TextView) v.findViewById(R.id.secondUserName);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.Categoria.setText(PastChallengeList.get(position).getCategoria_label());
        holder.FirstUserName.setText(PastChallengeList.get(position).getUser_challenge_1());
        holder.secondUserName.setText(PastChallengeList.get(position).getUser_challenge_2());
        return v;

    }

    static class ViewHolder {
        public TextView Categoria;
        public TextView FirstUserName;
        public TextView secondUserName;
    }

2 个答案:

答案 0 :(得分:1)

holder.Categoria.setBackgroundColor((Color.parseColor(PastChallengeList.get(位置).getColore_categoria()));

答案 1 :(得分:0)

尝试将此添加到您的getView

String label = PastChallengeList.get(position).getCategoria_label();

holder.Categoria.setText(label);

if (label.equalsIgnoreCase("apple"))
    holder.Categoria.setBackgroundColor(Color.parseColor("#ff0000"));
else if(...)
    holder.Categoria.setBackgroundColor(Color.parseColor("#ff0000"));