RecyclerView with different Cardlayouts

2020-05-23 08:57发布

问题:

What I'd like to do


At the moment I'm playing around with RecyclerView and CardView's. For now I wrote a RecyclerView.Adapter on which I can display the same CardView multiple times with different content - analog to the ListView with a BaseAdapter.

Now I'd like to write a RecyclerView with different CardView-Layout's (in style of Google Now). I've already searched for tutorials but didn't found anything useful about that topic. Does someone know, how this needs to be implemented? What needs to be done to realize that?

回答1:

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;
}