如果 Android 中的列表视图中的项目超过十个,列表视图中的每一行怎么可能有 5 种不同的颜色?
How it is possible 5 different colors of each row in listview if items are more then ten in listview in Android?
创建一个如下所示的数组作为列表项的编号我想你有五个项目:
int[] color_arr={Color.BLUE,Color.CYAN,Color.YELLOW,Color.GREEN,Color.RED};
并在自定义适配器的 getView()
方法中使用它,如下所示:-
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row=convertView;
row = inflater.inflate(R.layout.listview_custome, parent, false);
row.setBackgroundColor(color_arr[position]);// this set background color
TextView textview = (TextView) row.findViewById(R.id.tv_list);
ImageView imageview = (ImageView) row.findViewById(R.id.iv_list);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
我的问题是,如果列表项中的项目超过 5 个,怎么可能在列表视图中每行显示 5 种不同的颜色?
你在数组中有 5 个值,所以如果列表有超过 5 个项目肯定会崩溃,因为它找不到 data_image[5]
您可以使用%
运算符
imageview.setBackgroundColor(data_image[position % 5]);
对于第0-4个位置,它将按照现在的工作方式工作,对于第5个位置,它将设置位置0的颜色,对于第6个位置,它将设置位置1的颜色,依此类推...
试试这个,
row.setBackgroundColor(color_arr[position % color_arr.length]);
row.setBackgroundColor(color_arr[position % color_arr.length]);
创建一个如下所示的数组作为列表项的编号我想你有五个项目:
int[] color_arr={Color.BLUE,Color.CYAN,Color.YELLOW,Color.GREEN,Color.RED};
并在自定义适配器的 getView()
方法中使用它,如下所示:-
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row=convertView;
row = inflater.inflate(R.layout.listview_custome, parent, false);
row.setBackgroundColor(color_arr[position]);// this set background color
TextView textview = (TextView) row.findViewById(R.id.tv_list);
ImageView imageview = (ImageView) row.findViewById(R.id.iv_list);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
我的问题是,如果列表项中的项目超过 5 个,怎么可能在列表视图中每行显示 5 种不同的颜色?
你在数组中有 5 个值,所以如果列表有超过 5 个项目肯定会崩溃,因为它找不到 data_image[5]
您可以使用%
运算符
imageview.setBackgroundColor(data_image[position % 5]);
对于第0-4个位置,它将按照现在的工作方式工作,对于第5个位置,它将设置位置0的颜色,对于第6个位置,它将设置位置1的颜色,依此类推...
试试这个,
row.setBackgroundColor(color_arr[position % color_arr.length]);
row.setBackgroundColor(color_arr[position % color_arr.length]);