1

I have a listView and I want to put a drawable with a gradientColor as background. It's look Like this:

My list view

As you can see it's works thanks to this answer:

How to change color of drawable shapes in android but, I don't know why my First item take a transparent background and it's color is taken for the next item.

Here is my adapter code:

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

}

Community
  • 1
  • 1
Marlaurita
  • 583
  • 3
  • 11
  • 26

2 Answers2

3

Change:

 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;
dieter_h
  • 2,707
  • 1
  • 13
  • 19
0

Create a separate drawable for each item:

@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;
}
Simas
  • 43,548
  • 10
  • 88
  • 116