问题
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