Daniel Oliveira Daniel Oliveira - 1 year ago 47
Android Question

How to make RecyclerView stops recycling defined positions?

My problem is: I have a video streaming happening on one of the views inside the RecyclerView.

When the user scrolls, the view gets recycled and other cameras starts their own streaming on that recycled viewholder. This is bad for user interface since the streaming process takes some seconds to start.

How can I say to the RecyclerView: "Hey Recycler, please, do not recycle that exact position x and give that position ALWAYS the same viewholder you gave it the first time, instead of random one"?

Please someone help me =(

Answer Source

In your getItemViewType(int position) method of adapter, assign unique values for each video, so it will always return same ViewHolder for same video as you wish.

  • return unique positive number as type for each video type (here i used the adapter position as unique key)
  • return negative numbers for any non-video items. (nothing special here, just to avoid conflicts with video items, we use negative numbers for non-video items)

I hope you get the idea. cheers :)

    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be   contiguous
            return position;

            return -1;//indicates general type, if you have more types other than video, you can use -1,-2,-3 and so on.

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         switch (viewType) {
             case -1:  View view1 = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.general_item, parent, false);
                     return new GeneralViewHolder(view1);
             default:View view2 = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.video_item, parent, false);
                     return new VideoViewHolder(view2);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download