View Recycling not happens with Multiple Recyclerview inside NestedScrollView

若如初见. 提交于 2019-12-06 04:55:42

From my Experience I found that view recycling is not possible with multiple recyclerview's inside a NestedScrollView.

But I figure out the solution to show multiple Recyclerview's as per my requirement i want to show one Horizontal Recyclerview on top and one Vertical Recyclerview below it so what i did I am sharing may it helps someone.

I removed the NestedScrollView as parent of Recyclerview's and made Horizontal Recyclerview as HeaderView of Vertical Recyclerview.

code :

public class ListHeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
ArrayList<String> data;

public ListHeaderAdapter (ArrayList<String> data) {
    this.data = data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == TYPE_ITEM) {
        //inflate your layout and pass it to view holder
        return new VHItem(null);
    } else if (viewType == TYPE_HEADER) {
        //inflate your layout and pass it to view holder
        return new VHHeader(null);
    }
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
 int pos = position - 1; // for handling of Header view(use pos to fetch data from list)

    if (holder instanceof VHItem) {
        String dataItem = data.get(pos);
        //cast holder to VHItem and set data
    } else if (holder instanceof VHHeader) {
        //cast holder to VHHeader and set data for header.
    }
}

@Override
public int getItemCount() {
    return data.size()+ 1; // for handling of Header view
}

@Override
public int getItemViewType(int position) {
    if (isHeader(position))
        return TYPE_HEADER;

    return TYPE_ITEM;
}

public boolean isHeader(int position) {
    return position == 0;
}


class VHItem extends RecyclerView.ViewHolder {
    TextView title;

    public VHItem(View itemView) {
        super(itemView);
    }
}

class VHHeader extends RecyclerView.ViewHolder {
    Button button;

    public VHHeader(View itemView) {
        super(itemView);
    }
}
}

Note : same logic can be implemented to show Horizontal RecyclerView's at any Position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!