更改Listview中项目的背景颜色

时间:2015-04-09 16:07:31

标签: android android-listview

我有一个列表视图,其中包含一个可见的项目。

lv.getChildAt(0).setBackgroundColor(Color.RED));

这总是返回NullPointerException。

此外,我试图理解为什么lv.getChildCount()在使用中时会返回-1。

2 个答案:

答案 0 :(得分:0)

尝试listView.getAdapter()。getView(0,null,listView).setBackgroundColor(Color.RED);

android - listview get item view by position

答案 1 :(得分:0)

尝试更改适配器的背景颜色。这是一个关于如何改变的例子。

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public MySimpleArrayAdapter(Context context, String[] values) {
    super(context, R.layout.rowlayout, values);
    this.context = context;
    this.values = values;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
    textView.setText(values[position]);

    **// change the background
    if(position == 0)
       rowView.setBackgroundColor(Color.RED);**

    String s = values[position];
    if (s.startsWith("iPhone")) {
      imageView.setImageResource(R.drawable.no);
    } else {
      imageView.setImageResource(R.drawable.ok);
    }

    return rowView;
  }
}
相关问题