【问题标题】:Change color drawable gradient dynamically in adapter在适配器中动态更改颜色可绘制渐变
【发布时间】:2015-09-14 19:35:36
【问题描述】:

我有一个 listView,我想放置一个带有 gradientColor 作为背景的可绘制对象。它看起来像这样:

正如你所看到的,感谢这个答案:

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

}

【问题讨论】:

  • 代码或没有发生。
  • 准备好代码 =) @Simas

标签: android listview background adapter drawable


【解决方案1】:

变化:

 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;

【讨论】:

    【解决方案2】:

    为每个项目创建一个单独的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;
    }
    

    【讨论】:

    • 主要思想是动态地制作每个项目我都有一个对象,但谢谢:D
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多