Implement multiple ViewHolder types in RecycleView adapter

后端 未结 9 1701
迷失自我
迷失自我 2020-12-13 16:34

It\'s maybe a discussion not a question.

Normal way to implement multiple types

As you know, if we want to implement multiple types in RecyclerView

9条回答
  •  我在风中等你
    2020-12-13 16:47

    I use both, whatever is better for current task. I do respect the Single Responcibility principle. Each ViewHolder should do one task.

    If I have different view holder logic for different item types - I implement different view holders.

    If views for some different item types can be cast to same type and used without checks (for example, if list header and list footer are simple but different views) -- there is no sence in creating identical view holders with different views.

    That's the point. Different logic - different ViewHolders. Same logic - same ViewHolders.

    The ImageView and TextView example. If your view holder has some logic (for example, setting value) and it is different for different view types -- you should not mix them.

    This is bad example:

    class MultipleViewHolder extends RecyclerView.ViewHolder{
        TextView textView;
        ImageView imageView;
    
        MultipleViewHolder(View itemView, int type){
            super(itemView);
            if(type == 0){
                textView = (TextView)itemView.findViewById(xx);
            }else{
                imageView = (ImageView)itemView.findViewById(xx);
            }
        }
    
        void setItem(Drawable image){
            imageView.setImageDrawable(image);
        }
    
        void setItem(String text){
            textView.setText(text);
        }
    }
    

    If your ViewHolders don't have any logic, just holding views, it might be OK for simple cases. for example, if you bind views this way:

    @Override
    public void onBindViewHolder(ItemViewHolderBase holder, int position) {
        holder.setItem(mValues.get(position), position);
        if (getItemViewType(position) == 0) {
            holder.textView.setText((String)mItems.get(position));
        } else {
            int res = (int)mItems.get(position);
            holder.imageView.setImageResource(res);
        }
    }
    

提交回复
热议问题