recyclerView載入兩個佈局
阿新 • • 發佈:2019-01-08
一、想要實現載入兩套不同的佈局,只需在getItemViewType方法中返回不同的type,就可以在onCreateViewHolder方法中根據不同的type載入不同的佈局,不同的佈局,也同時也要實現不同的ViewHolder。onBindViewHolder方法也就可以根據不同的個佈局進行不同的操作
/** * 介面卡 */ class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = null; if (viewType == 0) { //根據不同的viewtype,載入不同的佈局 view = LayoutInflater.from(mActivity).inflate(R.layout.item_date, parent, false); return new MyViewHolderOne(view); } else { view = LayoutInflater.from(mActivity).inflate(R.layout.item_sweep_word, parent, false); return new MyViewHolderTwo(view); } } @Override public int getItemViewType(int position) { if (position>10) { //根據你的條件,返回不同的type return 0; } else { return 1; } } @Overridepublic void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { switch (getItemViewType(position)) { case 0: //不同的佈局,做不同的事 final MyViewHolderOne holderOne = (MyViewHolderOne) holder; break; case 1: final MyViewHolderTwo holderTwo = (MyViewHolderTwo) holder; } @Override public int getItemCount() { return list.size(); } public class MyViewHolderOne extends RecyclerView.ViewHolder { TextView item_word_date; //日期 public MyViewHolderOne(View view) { super(view); item_word_date = (TextView) view.findViewById(R.id.item_word_date); } } public class MyViewHolderTwo extends RecyclerView.ViewHolder { TextView item_word; //單詞 TextView item_word_mean; //詞義public MyViewHolderTwo(View view) { super(view); item_word = (TextView) view.findViewById(R.id.item_word); item_word_mean = (TextView) view.findViewById(R.id.item_word_mean);} } }