RecyclerView ViewHolder 中的 If 语句导致项目重复

If-statement in RecyclerView ViewHolder causes item duplication

如何使用自定义查看器实现 if 语句,而不会导致该视图在我滚动时多次出现在其他项目中(重复)?

我有一个 RecyclerView,它有一个按预期工作的自定义查看器。但是,我在每个列表项中都有一个小图像图标,只有在填写了列表项的 textView 之一时才会出现。当我尝试在自定义查看器中实现 if 语句时,它会导致在我滚动 RecyclerView 时复制该视图。

顺便说一下,如果我使用

@Override
public int getItemViewType(int position) {
     return position;
}

它可以防止重复,但也会导致 "swipe to dismiss" 功能出现动画问题。它不再平滑,但似乎有点闪烁或故障。下面是我的 ViewHolder:

private class CustomViewHolder extends RecyclerView.ViewHolder {
        ImageView candidateMainImage;
        ImageView careerIcon;
        TextView candidateCareerText;
        TextView candidateBioText;

        CustomViewHolder(View itemView) {
            super(itemView);
            candidateMainImage = itemView.findViewById(R.id.imageview_swipe_profile_container);
            careerIcon = itemView.findViewById(R.id.imageview_swipe_career_icon);
            candidateCareerText = itemView.findViewById(R.id.textview_swipe_career_display);
            candidateBioText = itemView.findViewById(R.id.textview_swipe_bio_display);
            mContext = itemView.getContext();
        }

        void bind(SwipeCandidate candidate) { 

            StorageReference candidateImageReference = candidate.getCandidateImageReference(); 

            GlideApp.with(candidateMainImage)
                    .load(candidateImageReference)
                    .into(candidateMainImage);

            String textCareer = candidate.getCandidateCareer();
            candidateCareerText.setText(textCareer);
            candidateCareerText.setVisibility(View.VISIBLE);

            String bio = candidate.getCandidateBio();
            candidateBioText.setText(bio);
            candidateBioText.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(candidate.getCandidateCareer())) {
                careerIcon.setVisibility(View.VISIBLE); // This gets duplicated into unwanted items
            }
        }
    }

ViewHolder在item之间循环使用,所以如果candidate.getCandidateCareer()not空的话,需要将状态重置回默认值:

            if (!TextUtils.isEmpty(candidate.getCandidateCareer())) {
                careerIcon.setVisibility(View.VISIBLE); // This gets duplicated into unwanted items
            } else {
                careerIcon.setVisibility(View.GONE); // or whatever your default is
            }