我有一个适配器,我传递颜色数组和文本数组>它不显示任何颜色数组的项目?
public class HoursFromToAdapter extends BaseAdapter{
private Context context;
private String[] mHoursRenge;
private int[] mColors;
private TextView mHoursRangeTxt;
private CardView mCardView;
public HoursFromToAdapter(Context context, String[] hoursRenge , int[] colors ) {
this.context=context;
this.mHoursRenge=hoursRenge;
this.mColors=colors;
}
@Override
public int getCount() {
/*return number of elements inside this array*/
return mHoursRenge.length;
}
@Override
public Object getItem(int position) {
/*return the item at posion -position-*/
return null;
}
@Override
public long getItemId(int position) {
/*return the id of the row which in this case the index of the array*/
return 0;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.day_item,parent,false);
View v;
LinearLayout ln;
if(convertView == null) {
v = new View(context);
v = inflater.inflate(R.layout.day_item, null);
ln=(LinearLayout)v.findViewById(R.id.card_containner);
mHoursRangeTxt= (TextView) v.findViewById(R.id.text_hours_from_to);
mHoursRangeTxt.setText(mHoursRenge[position]);
mCardView=(CardView)v.findViewById(R.id.card_day_item);
mCardView.setCardBackgroundColor(mColors[position]);
}else {
v = convertView;
}
return v;
}
}
当我从另一个类传递颜色数组时,它不显示但文本数组显示良好
String hoursArray[]={"7 am : 8 am" ,"8 am : 9 am","9 am : 10 am","10 am : 11 am","11 am : 12 pm","12 pm : 1 pm","1 pm : 2 pm","2 pm : 3 pm"};
int colorsArray[]={R.color.colorOrange,R.color.colorRed,R.color.colorOrange,R.color.colorOrange,R.color.colorRed,R.color.colorOrange,R.color.colorRed,R.color.colorOrange};
mHoursFromToAdapter=new HoursFromToAdapter(HomeActivity.this,hoursArray,colorsArray);
什么是无法在cardView上显示颜色数组的问题?
答案 0 :(得分:1)
setCardBackgroundColor
需要一种颜色,而不是呈现颜色的resId
颜色。
更改
mCardView.setCardBackgroundColor(mColors[position])
与
mCardView.setCardBackgroundColor(ContextCompat.getColor(context, mColors[position]))
我也会搬家
mHoursRangeTxt= (TextView) v.findViewById(R.id.text_hours_from_to);
mHoursRangeTxt.setText(mHoursRenge[position]);
mCardView=(CardView)v.findViewById(R.id.card_day_item);
mCardView.setCardBackgroundColor(mColors[position]);
在if else
子句之外并实现持有者模式