1

我有一个小问题要为我的列表视图行设置颜色。我使用下面的代码(用于适配器)为我的 listiview 设置颜色。我将两种颜色放入阵列中,效果很好。现在我想在我的列表中添加 5 种颜色。但是这段代码不起作用。我怎样才能做到这一点。

Custom_List_Adapter.java

private class Custom_List_Adapterextends BaseAdapter {
//Defining the background color of rows. The row will alternate between green light and green dark.
private int[] colors = new int[] { 0xAAf6ffc8, 0xAA538d00, 0xAAf6ddc8, 0xAA238d00, 0xAA788d00 };
private LayoutInflater mInflater;

//The variable that will hold our text data to be tied to list.
private String[] data;

public Custom_List_Adapter(Context context, String[] items) {
    mInflater = LayoutInflater.from(context);
    this.data = items;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

//A view to hold each row in the list
@Override
public View getView(int position, View convertView, ViewGroup parent) {

// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;

if (convertView == null) {
    convertView = mInflater.inflate(R.layout.row, null);

    holder = new ViewHolder();
    holder.text = (TextView) convertView.findViewById(R.id.headline);
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}
    // Bind the data efficiently with the holder.
    holder.text.setText(data[position]);

    //Set the background color depending of  odd/even colorPos result
    int colorPos = position % colors.length;
    convertView.setBackgroundColor(colors[colorPos]);

   return convertView;
}
}
4

0 回答 0