问题
I have the following issue. I populate a Recyclerview from my Fragment class. So far everything works out. However when I test my app and scroll up and down the populated recycler list the contents of each item change a.k.a. they get recycled...
How can I save each item's position and restore its content to the same position after scrolling?
Any suggestions?
回答1:
Good Question, this is your answer holder.setIsRecyclable(false).
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.product_recycle_buyer_list_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
holder.setIsRecyclable(false);
return holder;
}
回答2:
setIsRecyclable(false)
is bad solution, as it will create more and more views as you scroll, which ruins the whole point of using RecyclerView. Not only it takes more CPU, but the more you scroll and see new items, the more memory it will use. This is even worse, if you display bitmaps, as bitmaps tend to take huge amount of memory.
What you are supposed to do instead, is to implement onBindViewHolder
to bind the view to the data that it's supposed to have. Also use cache in case of using bitmaps.
You can look at a sample code I've made here, which asks of a different problem I'd like to solve.
回答3:
Doing this holder.setIsRecyclable(false);
will transform your RecyclerView
into a ListView
Instead do this
Just override this two methods inside your RecyclerAdapter
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
回答4:
In case someone experiences this, holder.setIsRecyclable(false)
will do it but then, it just makes the recycler view a list view, and also consumes more resources . Overriding the getItemViewType
and getItemId
should fix it.
来源:https://stackoverflow.com/questions/36250995/how-to-keep-recyclerview-items-at-same-position