0

I have been reading articles and questions about recycling a listItem rather than Inflating a new one which is costly. In particular I read this question and I understood the answers, but my question is: When we scroll down a list some listItems from the top disappear and they should be recycled and be shown again in the bottom of the List.

How does android determine the position of them? When we use the viewHolder = (ViewHolder)convertView.getTag; the viewHolder obviously holds the row who wants to be recycled and when we set View Elements by using viewHolder.txtName.setText(dataModel.getName()); I understand that we update the Elements in that particular viewHolder so how does it go to the bottom of the List?

I found this article very useful but there is not enough explanation and comments to make recycling clear for me. Android ListView with Custom Adapter

MohsenFM
  • 129
  • 1
  • 13
  • I know the pisition gets passed to the Method but it is the position of the recycled item? is it not ? If this item wants to be used again its position needs to change and go to the bottom of the list for example. So does android just stacks it up at the end of the list? – MohsenFM Jul 26 '17 at 14:51

1 Answers1

1

How does android determine the position of them?

The ListView adapter (ArrayAdapter for example) has ArrayAdapter.getView() and the equivalent adpater for RecyclerViews is RecyclerView.Adapter.onBindViewHolder(). They both have a position parameter in their method signatures:

// ListView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...
}

// RecyclerView
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ...
}

This is the list row position that has been scrolled into view, and needs to be bound to fill in the data.

Furthermore, RecyclerView.ViewHolder objects have the method getAdapterPosition(), so that you can find ViewHolder's list row position outside of the onCreateViewHolder() and onBindViewHolder() methods, for example in a click event handler.

See also:

Mr-IDE
  • 7,051
  • 1
  • 53
  • 59
  • so when android calls getView for the recycled item and we set it and return it, the android just put it at the end of the list? I am sorry this is somewhat confusing for me, I am very new to android and I appreciate your patience. – MohsenFM Jul 26 '17 at 15:10
  • @MohsenFM When Android calls `getView()` it will put the row at the exact required list position, not at the end of the list. When you scroll the list up or down and the row is off the screen, then sometime later the row will be deleted and garbage collected ('recycled'). But its template will be kept, so that new list rows can be scrolled into view with the same design. But you must always fill in the data for each recycled row that is scrolled into view, otherwise old data or glitches will appear. – Mr-IDE Jul 26 '17 at 16:05