RecyclerView多條目的實現
阿新 • • 發佈:2018-12-10
首先實現大體思路是
1.搭建環境(新增依賴,添加布局控制元件,初始化控制元件)
* 2.初始化資料
* 3.建立介面卡
* 4.設定介面卡及佈局管理物件
* <p>
* 什麼是程式碼優化:1.可讀性強 2.減少複雜邏輯 3.擴充套件性強
然後採用的是基類抽取的方式將
/**
* 子類共有,且實現相同的邏輯,抽取到基類中
* 子類共有,但實現不同的邏輯,以抽象方法在基類中使用
*/
因為這個介面返回資料生成的bean類中並沒有返回type屬性所以我是自己手動寫的常量表示3種不同類別
//3個條目的父類 public abstract class FatherViewHolder extends RecyclerView.ViewHolder { public FatherViewHolder(@NonNull View itemView) { super(itemView); } public abstract void bindHolder(List<News.DataBean> list, int i); }
//3個子類條目
public class OneViewHolder extends FatherViewHolder { private final SimpleDraweeView img_item; private final TextView text_name_item; private final TextView text_title_item; public OneViewHolder(@NonNull View itemView) { super(itemView); img_item = itemView.findViewById(R.id.img_item); text_name_item = itemView.findViewById(R.id.text_name_item); text_title_item=itemView.findViewById(R.id.text_title_item); } @Override public void bindHolder(List<News.DataBean> list, int i) { text_name_item.setText(list.get(i).getAuthor_name()); text_title_item.setText(list.get(i).getTitle()); Uri parse = Uri.parse(list.get(i).getThumbnail_pic_s()); img_item.setImageURI(parse); } }
//在填充佈局的時候要注意 mLayoutInflater=LayoutInflater.from(context); 如果沒有寫這個而是直接生成構造方法後期執行是會產生空指標異常 public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public static final int TYPE_ONE = 1; public static final int TYPE_TWO = 2; public static final int TYPE_THREE = 3; private ArrayList<News.DataBean> nlist; private Context context; private LayoutInflater mLayoutInflater; private OneViewHolder oneViewHolder; private TwoViewHolder twoViewHolder; private ThreeViewHolder threeViewHolder; public MyAdapter(ArrayList<News.DataBean> nlist, Context context) { this.nlist = nlist; mLayoutInflater=LayoutInflater.from(context); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case TYPE_ONE: return new OneViewHolder(mLayoutInflater.inflate(R.layout.item, parent, false)); case TYPE_TWO: return new TwoViewHolder(mLayoutInflater.inflate(R.layout.item1, parent, false)); case TYPE_THREE: return new ThreeViewHolder(mLayoutInflater.inflate(R.layout.item2, parent, false)); } return null; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { ((FatherViewHolder)viewHolder).bindHolder(nlist,i); } @Override public int getItemCount() { return nlist.size(); } @Override public int getItemViewType(int position) { if (!TextUtils.isEmpty(nlist.get(position).getThumbnail_pic_s03())){ return TYPE_THREE; }else if (!TextUtils.isEmpty(nlist.get(position).getThumbnail_pic_s02())){ return TYPE_TWO; }else { return TYPE_ONE; } } }