RecyclerView with different Cardlayouts

后端 未结 1 920
北海茫月
北海茫月 2021-02-04 09:20

What I\'d like to do


At the moment I\'m playing around with RecyclerView and CardView\'s. For now I wrote a Recycl

1条回答
  •  迷失自我
    2021-02-04 09:43

    To achieve what you want you need to override getItemViewType(position) on your RecyclerView.Adapter, Where you'll return an int telling you what kind of view will be used to represent this position.

    Next you will create different ViewHolders on createViewHolder (parent,viewType) which will keep the references to each distinct CardLayout in your case.

    Then on bindViewHolder(holder, position) you can create a switch statement or if else cases to go through your list of possible views and fill them with data.

    Sample code below:

    public GeneralViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    
        GeneralViewHolder holder;
        View v;
        Context context = viewGroup.getContext();
    
        if (viewType == FIRST_TYPE) {
            v = LayoutInflater.from(context)
                    .inflate(R.layout.first_card, viewGroup, false);
    
            holder = new FirstTypeViewHolder(v); //Of type GeneralViewHolder
        } else {
            v = LayoutInflater.from(context)
                    .inflate(R.layout.second_card, viewGroup, false);
            holder = new SecondTypeViewHolder(v);
        }
    
        return holder;
    }
    
    public void onBindViewHolder(GeneralViewHolder viewHolder, int i) {
        if(getItemViewType(i)==FIRST_TYPE) {
            FirstTypeViewHolder holder1 = (FirstTypeViewHolder)viewHolder;
        } else {
            SecondTypeViewHolder holder1 = (SecondTypeViewHolder)viewHolder;
        }
    }
    
    public int getItemViewType (int position) {
        //Some logic to know which type will come next;
        return Math.random()<0.5 ? FIRST_TYPE : SECOND_TYPE;
    }
    

    0 讨论(0)
提交回复
热议问题