RecyclerView with different Cardlayouts

匿名 (未验证) 提交于 2019-12-03 02:48:02

问题:

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


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