在适配器中动态更改颜色可绘制渐变

时间:2015-09-14 19:35:36

标签: android listview background adapter drawable

我有一个listView,我想把一个带有gradientColor的drawable作为背景。它看起来像这样:

My list view

由于这个答案,你可以看到它的作用:

How to change color of drawable shapes in android但是,我不知道为什么我的第一个项目采用透明背景,并为下一个项目拍摄颜色。

这是我的适配器代码:

public class PromoAdapter extends ArrayAdapter {

private Context context;
private ArrayList<PromoObject> originalData = null;
private GradientDrawable gradient;
public PromoAdapter(Context context, ArrayList<PromoObject> listArray) {
    super(context, R.layout.home_promo_item);
    this.context = context;
    this.originalData = listArray ;
}

public static class Row
{
    public RelativeLayout layout;
    public TextView labelPromo;
}

@Override
public int getCount() {
    return originalData.size();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View rowView = convertView;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        rowView = inflater.inflate(R.layout.home_promo_item, null);
        // configure view holder
        Row viewHolder = new Row();

        viewHolder.labelPromo = (TextView) rowView.findViewById(R.id.label_promo);

        rowView.setTag(viewHolder);
    }
    Row holder = (Row) rowView.getTag();
    PromoObject itm = originalData.get(position);

    holder.labelPromo.setText(itm.getPromoValue());

    rowView.setBackgroundDrawable(gradient);
    gradient = new GradientDrawable(
            GradientDrawable.Orientation.LEFT_RIGHT,
            new int[] {0xFF616261,0xFF131313});
    gradient.setCornerRadius(15f);

    return rowView;
}

}

2 个答案:

答案 0 :(得分:3)

变化:

 holder.labelPromo.setText(itm.getPromoValue());
 if(position==0){

        gradient = new GradientDrawable(
            GradientDrawable.Orientation.LEFT_RIGHT,
            new int[] {0xFF616261,0xFF131313});
        gradient.setCornerRadius(15f);

        rowView.setBackgroundDrawable(gradient);
 }else{
        //default drawable or color
        rowView.setBackgroundDrawable(default);
 }
 return rowView;

答案 1 :(得分:0)

为每个项目创建一个单独的drawable:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  ...

  GradientDrawable gradient = new GradientDrawable(
      GradientDrawable.Orientation.LEFT_RIGHT,
      new int[] {0xFF616261,0xFF131313});
  gradient.setCornerRadius(15f);
  rowView.setBackgroundDrawable(gradient);

  return rowView;
}
相关问题