0

I have a listview with a single item in it which is visible.

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

This always returns a NullPointerException.

Also Im trying to understand why lv.getChildCount() returns -1 when there's a view in use.

JustAGuy
  • 3,773
  • 8
  • 33
  • 49

2 Answers2

0

try listView.getAdapter().getView(0, null, listView).setBackgroundColor(Color.RED);

android - listview get item view by position

Community
  • 1
  • 1
StiggyBr0
  • 93
  • 7
0

Try to change background color from your adapter. Here is an example about how to change.

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;
  }
}
savepopulation
  • 10,674
  • 4
  • 47
  • 68
  • It should be: **// change the background if(position == 0) rowView.setBackgroundColor(Color.RED); else rowView.setBackgroundColor(Color.BLACK);** Handle both cases else it will give unexpected results after view reuse. – seema Apr 09 '15 at 18:03