Set text and show TextView conditionally in a RecyclerView

怎甘沉沦 提交于 2019-12-24 19:15:12

问题


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

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