Problems with dynamic views inside recycler view

核能气质少年 提交于 2019-12-23 10:28:57

问题


I'm using recycler view to show list of items which contains grid layout of images. The grid layout is added dynamically to the list item inside "onBindViewHolder" method on recycler view adapter. Now problem is that the grid layout views are recreated on every scroll. I don't want those views to be recreated on scroll. How to deal with it??

Here is the code snippet

 @Override
    public void onBindViewHolder(final PersonViewHolder personViewHolder, final int i) {

                GridLayout feedGrid = new GridLayout(context);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dipToPixels(context,HomePage.SCREEN_WIDTH),dipToPixels(context,HomePage.SCREEN_WIDTH));
                feedGrid.setLayoutParams(layoutParams);
                feedGrid.setColumnCount(1);

                imgArr = new ImageView[num];
                imgArr[0] = new ImageView(context);
                GridLayout.Spec row = GridLayout.spec(0, 1);
                GridLayout.Spec colspan = GridLayout.spec(0, 1);
                GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(row, colspan);
                gridLayoutParam.setGravity(Gravity.FILL);

                    Picasso.with(context).load(urlArr.get(0)).error(mDrawable).placeholder(mDrawable).into(imgArr[0], new Callback() {
                        @Override
                        public void onSuccess() {
                            personViewHolder.feedGridLayout.setVisibility(View.VISIBLE);
                            personViewHolder.loadImg.setVisibility(View.GONE);
                        }

                        @Override
                        public void onError() {
                            personViewHolder.feedGridLayout.setVisibility(View.GONE);
                            personViewHolder.loadImg.setVisibility(View.VISIBLE);

                        }

                    });



                feedGrid.addView(imgArr[0], gridLayoutParam);

                personViewHolder.feedGridLayout.removeAllViews();

                personViewHolder.feedGridLayout.addView(feedGrid);

}

回答1:


This is how I solved a very similar problem.

In your adapter you override onViewRecycled and remove the views of your gridLayout there instead of onBindViewHolder.

@Override
    public void onViewRecycled(PersonViewHolder personViewHolder) {
        super.onViewRecycled(personViewHolder);
        personViewHolder.feedGridLayout.removeAllViews();
    }

Remove personViewHolder.feedGridLayout.removeAllViews(); from your onBindViewHolder.

Let me know if that fixes it.



来源:https://stackoverflow.com/questions/33167822/problems-with-dynamic-views-inside-recycler-view

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