1

My problem is that when I'm scrolling a list view I'm getting wrong convertView, but the position is right.

I have 3 items in my Listview, on load 'position' parameter is called with index '0' and convertView is null.

When I scroll one by one, to the next item 'position' is '1' and convertView is null also.

The problem is on item 3, the 'position' is '2' BUT the 'convertView' is not null, it is populated by the first item convertView.

Why is that ?

 public View getView(final int position, View convertView, ViewGroup parent) {
        View itemView = convertView;
        if (itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.post_layout, parent, false);

            postViewHolder                              = new PostViewHolder();
            postViewHolder.commentsImageButton          = (ImageButton) itemView.findViewById(R.id.postAddCommentsImageButton);

            itemView.setTag(postViewHolder);
        }else{
            postViewHolder = (PostViewHolder) itemView.getTag();
        }

}

EitanG
  • 221
  • 4
  • 19

2 Answers2

1

You will only get N null items in your listView, this value N will change depending on how many rows enter in your screen.

For example if in your screen there are 3 rows, you will probably have 4 or 5 row items. This is because Android recycle the old views into new ones.

If you need to keep track of the holder position move your postViewHolder.position out of your if / else statement.

Hope it helps.

zozelfelfo
  • 3,776
  • 2
  • 21
  • 35
  • Thanks for your answer. I've removed the postViewHolder.position from the question, it is irrelevant. – EitanG Jul 22 '14 at 08:50
  • Thanks for your answer. I understand that it recycle old views, but with viewHolder Pattern it will load a recycled convertView, which is wrong, all the views from 'findViewByID' will direct the recycled convertView and will not create a new one. – EitanG Jul 22 '14 at 08:56
  • And why do you need to create a new one? That is how ListViews work. If you have more items in your listviews, the will be recycled into these N views which are the views you need to display the information. – zozelfelfo Jul 22 '14 at 09:16
0

Try This

public View getView(final int position, View convertView, ViewGroup parent) {
        View itemView = convertView;
        PostViewHolder postViewHolder = null;
        if (itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.post_layout, parent, false);
            postViewHolder                              = new PostViewHolder();
            postViewHolder.commentsImageButton          = (ImageButton) itemView.findViewById(R.id.postAddCommentsImageButton);

            itemView.setTag(postViewHolder);
        }else{
            postViewHolder = (PostViewHolder) itemView.getTag();
        }
        postViewHolder.position    = position;
        :do your stuff with postViewHolder
        :
        return itemView;
}
Janoti
  • 36
  • 5