RecyclerView inside NestedScrollView causes RecyclerView to inflate all elements

北城余情 提交于 2019-12-02 05:25:52

I too have come across this issue... This is because both scrollview and RecyclerView are different in loading data, since the ScrollView acts as the parent in this case and we are using the below line in our code.

setNestedScrollingEnabled(false);

This will make the scroll slow and hang issue based on the Recyclerview data.

One way which I have used to solve this issue is adding header to the Recyclerview..

Here I'll explain it clearly.

lets assume this recyclerview is in our activity.

<android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />

The adapter class will be like this, where we will add the header

public class SampleAdapter extends RecyclerView.Adapter {


    private final int BODY = 1;
    private final int HEADER = 2;

    private List<String> data = null;

    SampleAdapter(List<String> data) {
        this.data = data;
    }


    @Override
    public int getItemViewType(int position) {

        if (position == 0) {
            return HEADER;
        }

        return BODY;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {

            case HEADER:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_header_layout, parent, false);
                return new HeaderViewHolder(view);

            default:
                //Setting the Body view...
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_details, parent, false);
                return new BodyViewHolder(view);
        }
    }

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

        if (holder instanceof BodyViewHolder) {
            //Set the body content....
            if (data != null && data.size() > 0) {
                /** Since we have added one cell for header,
                 * we need to decrement the position and render the body view.
                 *
                 */
                int bodyPosition = position - 1;

            }
        } else if (holder instanceof HeaderViewHolder) {
            //Set the header content...
        }
    }

    @Override
    public int getItemCount() {
        //Sice we are going to add header, we are supposed increase the count by one...
        return data.size() + 1;
    }
}

by this there is no need for NestedScrollView and all the view will work in RecyclerView behavior...

Hope this is helpful :)

If you have large amount of data to display,show only some numbers of data first time than on scroll use loadMoreListener to get next data.

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