How do you set the color of a cell in a ListView?

Setting the color of cells in a ListView can be achieved using an adapter.

Firstly, in the getView method of the adapter, set the background color of the cell. This can be achieved by setting the background color of the View or using a background Drawable. Different colors can be set according to the requirements.

The code example is as follows:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // 获取当前位置的数据
    Item item = getItem(position);

    // 创建或复用convertView
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
    }

    // 设置单元格的背景颜色
    if (position % 2 == 0) {
        convertView.setBackgroundColor(Color.RED);
    } else {
        convertView.setBackgroundColor(Color.BLUE);
    }

    // 更新单元格的其他内容

    return convertView;
}

In the above example, the background color of cells is set based on the parity of their position, with cells at even positions having a red background color, and cells at odd positions having a blue background color.

Note: The above code is just an example, when actually using it, you need to set the background color of the cells according to your own needs.

bannerAds