Recycler多布局(适配器)之无Type值

Posted ggjy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Recycler多布局(适配器)之无Type值相关的知识,希望对你有一定的参考价值。

RecyclerView简易适配器 --无Type值。

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {


    private List<MyData.ResultBean.DataBean> mList;
    private Context mContext;
    private final static int ITEM_ONE = 1;
    private final static int ITEM_TWO = 2;

public MyAdapter(List<MyData.ResultBean.DataBean> mList, Context mContext) {
this.mList = mList;
this.mContext = mContext;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view;
RecyclerView.ViewHolder holder;
if (viewType == ITEM_ONE) {
view = inflater.inflate(R.layout.recy_item_one, parent, false);
holder = new HolderOne(view);
} else {
view = inflater.inflate(R.layout.recy_item_two, parent, false);
holder = new HolderTwo(view);
}
view.setOnClickListener(this);
return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyData.ResultBean.DataBean dataBean = mList.get(position);
if (holder instanceof HolderOne) {
((HolderOne) holder).mTextOne.setText(dataBean.getTitle());
Picasso.with(mContext).load(dataBean.getThumbnail_pic_s()).into(((HolderOne) holder).mImageOne);
((HolderOne) holder).itemView.setTag(position);
} else {
((HolderTwo) holder).mTextTwo.setText(dataBean.getTitle());
Picasso.with(mContext).load(dataBean.getThumbnail_pic_s()).into(((HolderTwo) holder).mImageTwo);
((HolderTwo) holder).itemView.setTag(position);
}
}

@Override
public int getItemCount() {
return mList.isEmpty() ? 0 : mList.size();
}

//控制到底用的是那个模板
@Override
public int getItemViewType(int position) {
if (position % 2 == 0) {
return ITEM_ONE;
} else {
return ITEM_TWO;
}
}


class HolderOne extends RecyclerView.ViewHolder {
private TextView mTextOne;
private ImageView mImageOne;

public HolderOne(View itemView) {
super(itemView);
mTextOne = (TextView) itemView.findViewById(R.id.Recy_One_Text);
mImageOne = (ImageView) itemView.findViewById(R.id.Recy_One_Image);
}
}

class HolderTwo extends RecyclerView.ViewHolder {
private TextView mTextTwo;
private ImageView mImageTwo;

public HolderTwo(View itemView) {
super(itemView);
mTextTwo = (TextView) itemView.findViewById(R.id.Recy_Two_Text);
mImageTwo = (ImageView) itemView.findViewById(R.id.Recy_Two_Image);
}
}

public interface OnItemClick {
void setOnItem(View v, int position);
}

private OnItemClick onitem;

@Override
public void onClick(View v) {
if (onitem != null) {
onitem.setOnItem(v, (int) v.getTag());
}
}

public void setOnItemListener(OnItemClick item) {
this.onitem = item;
}
}

以上是关于Recycler多布局(适配器)之无Type值的主要内容,如果未能解决你的问题,请参考以下文章

Android recycler view onItemClick 识别适配器

RecycleView的多布局

Recycler View项目onClick无法正常工作。(工作异常)

recyclerview的使用

在Recycler视图中使用数组列表

BaseQuickAdapter万能适配器--分类型实现多布局效果的3个适配器