赞
踩
在显示列表时,我们需要的数据有可能需要不止一种item,对于有多种复杂数据的数据源,就需要以不同的样式显示出来,先看一下效果
我们都知道,在ListView的Adapter中,我们可以通过重写int getItemViewType(int position)
和 int getViewTypeCount()
这两个方法来实现定义多种布局的type。那么在RecyclerView的Adapter中,是否也有类似的方法呢?
没错,是有的,就是int getItemViewType(int position)
方法。
接下来,直接看代码
MultipleItemsAdapter.xml
package com.zou.zohar.recyclerviewdemo.ui.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.zou.zohar.recyclerviewdemo.R;
import com.zou.zohar.recyclerviewdemo.ui.model.ImageItem;
import com.zou.zohar.recyclerviewdemo.ui.model.MultipleItem;
import com.zou.zohar.recyclerviewdemo.ui.model.TextImageItem;
import com.zou.zohar.recyclerviewdemo.ui.model.TextItem;
import java.util.List;
/**
* Created by Zohar on 2017/5/21.
* desc:多种Item布局的Adapter
*/
public class MultipleItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/**
* 定义三种Type
*/
private final int ITEM_TYPE_TEXT = 0;
private final int ITEM_TYPE_IMAGE = 1;
private final int ITEM_TYPE_TEXT_IMAGE = 2;
private Context mContext;
private List<MultipleItem> dataList;
public MultipleItemsAdapter(Context mContext, @NonNull List<MultipleItem> dataList) {
this.mContext = mContext;
this.dataList = dataList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/**
* 根据不同的Type返回对应的ViewHolder
*/
View view;
if (viewType == ITEM_TYPE_TEXT) {
view = LayoutInflater.from(mContext).inflate(R.layout.multiple_item_layout_text, parent, false);
return new TextHolder(view);
} else if (viewType == ITEM_TYPE_IMAGE) {
view = LayoutInflater.from(mContext).inflate(R.layout.multiple_item_layout_image, parent, false);
return new ImageHolder(view);
} else if (viewType == ITEM_TYPE_TEXT_IMAGE) {
view = LayoutInflater.from(mContext).inflate(R.layout.multiple_item_layout_text_image, parent, false);
return new TextImageHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
/**
* 根据不同的Type,设置对应的ViewHolder
*/
switch (dataList.get(position).getItemType()) {
case TEXT:
TextItem textItem = (TextItem) dataList.get(position);
TextHolder textHolder = (TextHolder) holder;
textHolder.tvText.setText(textItem.getText());
break;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。