Problems with dynamic views in recycler view

I am using a recycler view to display a list of items that contains a grid of image layouts. The grid layout is dynamically added to the list item inside the onBindViewHolder method in the recycler view adapter. Now the problem is that the grid layout representations are recreated on each scroll. I do not want these views recreated in the scroll. How to deal with it?

Here is a snippet of code

@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); } 
+5
source share
1 answer

This is how I solved a very similar problem.

In your adapter, you override onViewRecycled and delete 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 this fixes.

0
source

Source: https://habr.com/ru/post/1233853/


All Articles