I have a custom base adapter that will take in an arraylist of data. From here it will fill out a grid view with custom buttons. It does so perfectly and fills up the gridvi
Prevent the adapter from recycling views on scroll
Just don't use the convertView
param passed to getView()
and always return a freshly generated View
.
However, this is a bad solution in terms of performance. Instead, your goal should not be to prevent recycling but to recycle correcltly: Your getView()
should reset the convertView
to it's pristine state.
So, if there's a change that some of your Button
's properties are changed from their non-default values, reset them back to defaults in getView()
.
I had this exact problem So I added some code to check every view that it was not highlighted and when it found the highlighted view it changed it back.
//--------SET-FOREGROUND-IMAGE-(BORDER)------------
/*If the user clicks on an item and then scrolls down so the selected item is no longer in view Then the
Item that the user clicked on will be recycled with the foreground image.
This is BAD because when the user sees the selected item (as distinguished by it's different border)
it will be holding different data from a different data model item.
These following lines of code will change the colour of any non selected item back to normal and they will
colour of the selected views appropriately*/
if(currentLine.getLineId() == clickedId)
{recycleHolder.cardView.setForeground(parentActivity.getResources().getDrawable(R.drawable.card_view_border_selected));}
else
{recycleHolder.cardView.setForeground(parentActivity.getResources().getDrawable(R.drawable.card_view_border));}
and this code is placed within
@Override
public void onBindViewHolder(final RecyclableViewHolder recycleHolder, int i)
{
}
public View getView(int position, View convertView, ViewGroup parent) {
View itemview = null;
itemview = getLayoutInflater().inflate(R.layout.ordermini, parent,false);
}
This will help to inflate a new view
A better approach would be using
recyclerView.getRecycledViewPool().setMaxRecycledViews(VIEW_TYPE,0);
You must note that this may reduce the performance of your RecyclerView.
You can Override the getItemViewType method as mentioned below
@Override
public int getItemViewType(int position) {
if (position == feedElements.size())
return 3;
else if (feedElements.get(position).getType() == 1)
return 1;
else
return 2;
}