多种布局主要重写Adapter中的 getItemViewType 方法:
@Override
public int getItemViewType(int position) {
return mDatas.get(position).getViewId();
}
这里我给列表每个元素设置了视图id,在getItemViewType 中直接返回对应视图的LayoutId。
然后再 onCreateViewHolder 中根据 viewType 使用不用的 LayoutId 创建不同的 ViewHolder 并返回(此处的viewType既getItemViewType的返回值LayoutId):
//此处viewType既layoutId
@Override
public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return CommonViewHolder.get(mContext,null,parent,viewType,-1);
}
CommonViewHolder.get()方法实现如下,传入的第四个参数就是layoutId,然后通过LayoutInflater加载该布局,返回holder
public static CommonViewHolder get(Context context, View convertView,
ViewGroup parent, int layoutId, int position)
{
if (convertView == null)
{
View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
false);
CommonViewHolder holder = new CommonViewHolder(context, itemView, parent, position);
holder.mLayoutId = layoutId;
return holder;
} else
{
CommonViewHolder holder = (CommonViewHolder) convertView.getTag();
holder.mPosition = position;
return holder;
}
}
接下来在 onBindViewHolder 中根据不同的布局加载不同的数据:
@Override
public void onBindViewHolder(CommonViewHolder holder, final int position) {
if(mItemClickListener != null){
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mItemClickListener != null && view != null && recyclerView != null){
int pos = recyclerView.getChildAdapterPosition(view);
if(mDatas.get(pos).getViewId() == R.layout.item_search_two){
mItemClickListener.onItemThreeClick(recyclerView,view,position);
}else if (mDatas.get(pos).getViewId() == R.layout.item_search_three){
mItemClickListener.onItemTwoClick(recyclerView,view,position);
}
}
}
});
convert(holder,mDatas.get(position));
}
@Override
public void convert(CommonViewHolder holder, AudioBean audioBean) {
Bitmap bitmap;
BitmapFactory.Options op = new BitmapFactory.Options();
op.inSampleSize = 6;
switch (audioBean.getViewId()){
case R.layout.item_search_three:
holder.setText(R.id.tv_title,audioBean.getTitle());
holder.setText(R.id.tv_describe,audioBean.getArtist());
bitmap = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.taylor_swift,op);
BitmapDrawable bd = new BitmapDrawable(mContext.getResources(),bitmap);
holder.setImageDrawable(R.id.iv_image,bd);
break;
case R.layout.item_search_two:
holder.setText(R.id.tv_title,audioBean.getTitle());
holder.setText(R.id.tv_describe,audioBean.getArtist());
bitmap = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.taylor_swift,op);
holder.setImageBitmap(R.id.iv_image,bitmap);
break;
}
}
如果遇到图片加载不出的情况,可以试试:
RecyclerView.RecycledViewPool pool =recyclerView.getRecycledViewPool();
pool.setMaxRecycledViews(0,10);
recyclerView.setRecycledViewPool(pool);