问题
I'm displaying a list alphabetically in a RecyclerView, each letter group should have a letter displayed to the left side, once, at the top of each group. The divider line is rendered in an ItemDecorator.
I'm trying to solve this in onBindViewHolder. The initial layout works fine. As I scroll from the top to bottom everthing is as expected. But when I scroll back up the the initial/capital letter goes missing or it gets reordered.
Scrolling down is showing the initial letter conditionally as expected:
After scrolling back up k is missing in this example, :
public void onBindViewHolder(WordItemViewHolder wordItemViewHolder, final int position) {
final WordModel wordModel = wordModels.get(position);
wordItemViewHolder.textView.setText(wordModel.getWord());
String word = wordModel.getWord();
String currentFirstLetter = word.substring(0,1);
if(maxListRendered <= position){
if(!previousLetter.contentEquals(currentFirstLetter) || position == 0){
wordItemViewHolder.initialView.setText(currentFirstLetter.toUpperCase());
wordItemViewHolder.initialView.setVisibility(View.VISIBLE);
previousLetter = currentFirstLetter;
}else{
wordItemViewHolder.initialView.setVisibility(View.INVISIBLE);
}
}
maxListRendered++;//initialised as 0 in attempt to track calls to onBindViewHolder
}
Any help appreciated, thank you.
回答1:
Get rid of maxListRendered and previousLetter to begin with - that's dangerous to do and will cause issues.
Instead check the index above the current. Also instead of showing and hiding elements, I'd recommend having different view types by overriding getItemViewType
- that makes them being recycled separately so they can have different views.
来源:https://stackoverflow.com/questions/45821165/set-text-and-show-textview-conditionally-in-a-recyclerview