如何为listview中的每一行设置不同的背景颜色?

10 android listview

我想在listview的每一行中设置不同的背景颜色?我使用自定义适配器列表视图.它应该出现在活动loads.static不同颜色的行时.

Sam*_*iya 13

getView(...) method

if (position == 0) {
    view.setBackgroundResource(R.drawable.bg_list_even);
} else if (position == 1) {
    view.setBackgroundResource(R.drawable.bg_list_odd);
} else...
Run Code Online (Sandbox Code Playgroud)

更新::

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder holder;

    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        view = inflater.inflate(R.layout.row, null);

        holder = new ViewHolder();
        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    holder.title = (TextView) view.findViewById(R.id.txttitle);
    holder.description = (TextView) view.findViewById(R.id.txtdesc);

    holder.title.setText("Title" + position);
    holder.description.setText("Desc" + position);

    //here set your color as per position

    if (position == 0) {
        view.setBackgroundResource(R.drawable.bg_list_even);
    } else if (position == 1) {
        view.setBackgroundResource(R.drawable.bg_list_odd);
    }
    return view;
}
Run Code Online (Sandbox Code Playgroud)

持有人阶级

public class ViewHolder {

    public TextView title;
    public TextView description;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案...... //偶数和奇数行... if((位置%2)== 0){view.setBackgroundResource(R.drawable.bg_list_even); } else {view.setBackgroundResource(R.drawable.bg_list_odd); 你在你的网站上有很好的解决方案! (2认同)

Kha*_*han 5

如下所示制作一个数组作为列表项目的数量我想你有五个项目

 int[] color_arr={Color.BLUE,Color.CYAN,Color.DKGRAY,Color.GREEN,Color.RED};
Run Code Online (Sandbox Code Playgroud)

以及如下所示在客户端适配器的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);

    }
Run Code Online (Sandbox Code Playgroud)


Her*_*rry 4

正如您所说,您已对列表视图使用自定义适配器,那么您需要执行的操作如下。在getView适配器的方法中,您需要设置列表行 xml 父视图的背景颜色。