1

I have problem with my ListView. I want to set every second element in listView to have its background transparent. I use following code:

public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.list_row_object, null);

            Drawable backgroundDrawable = context.getResources().getDrawable(R.drawable.abstract_gray);
            if((int)(position%2)==1)
                backgroundDrawable.mutate().setAlpha(ToolsAndConstants.BACKGROUND_TRANSPARENCY);

            // It is not working sometimes when I just use v.setBackground(backgroundDrawable); here. Why?
            v.setBackground(backgroundDrawable.mutate());

            holder = new ViewHolder();
            holder.rowNumber = (TextView) v.findViewById(R.id.list_row2_number);
            holder.character = (TextView) v.findViewById(R.id.list_row2_char);
            holder.strokesNumber = (TextView) v.findViewById(R.id.list_row2_strokes_number);
            v.setTag(holder);
        }
        else
            holder = (ViewHolder)v.getTag();

        (...)
        (...)
        (...)
        return v;
    }

The list loads fine, but the problem is that when I scroll it several times up and down it gets totally crazy (?Randomly? sets transparent background and solid background). Please refer to the screenshots below (before and after scrolling):

Before:

enter image description here

After:

enter image description here

Outside adapter class I just add onClickListener in which I replace fragment with different one. There is no onScrollListener etc. Why the layout is changing?

Marek
  • 3,935
  • 10
  • 46
  • 70

1 Answers1

1

This is because the view of list item is reused, you need to reset background each time when the getView method being invoked not only when convertView is null. e.g.

public View getView(int position, View convertView, ViewGroup parent)
     ....
     if (v == null) {
         // Inflate the view without set the background
     }

     // Set the background based on position
     ...
}
Qiang Jin
  • 4,427
  • 19
  • 16
  • But when I scroll the list, getView is not invoked...And before that layout is good. But your solution fixed the problem - I totally don't understand why. If the getView method is not invoked during scrolling, and before scrolling everything looks good, why your answer is a solution? – Marek Jun 07 '13 at 01:20
  • Also please tell me why I have to use mutate() twice. – Marek Jun 07 '13 at 01:32
  • @Marek getView will be invoked during the scroll when there's new list item to display. i don't know about the mutate, i would suggest to use two different drawable, one for the transparency and one for another. – Qiang Jin Jun 07 '13 at 01:55