- 添加依賴
compile 'com.android.support:recyclerview-v7:25.3.0'
- 創(chuàng)建bean對(duì)象
這里的bean對(duì)象可以寫(xiě)成兩個(gè)部分,一部分表示原始數(shù)據(jù),一部分在RecycelView進(jìn)行顯示。
這樣說(shuō)可能有點(diǎn)抽象,舉個(gè)例子說(shuō)明。我需要顯示如圖的樣式:

我創(chuàng)建兩個(gè)bean對(duì)象,一個(gè)用于數(shù)據(jù)的傳遞,一個(gè)在adapter中用于item的顯示。InfoBean用于控制數(shù)據(jù)。ItemHolder用于顯示數(shù)據(jù)
代碼請(qǐng)參考:
infoBean對(duì)象如下:
package com.hut.reoger.studentsrecycleview.bean;
/**
* Created by 24540 on 2017/3/28.
*/
public class InfoBean {
private int id;
private String title;
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
ItemHolder代碼如下:
public class ItemHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView teTitle;
public TextView teContent;
public ItemHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.item_image);
teTitle = (TextView) itemView.findViewById(R.id.item_title);
teContent = (TextView) itemView.findViewById(R.id.item_content);
}
}
這里需要記住的是,這個(gè)類需要繼承ViewHolder。當(dāng)然,這個(gè)類寫(xiě)在adapter中也完全是ok的。
- 創(chuàng)建adapter對(duì)象
詳細(xì)參照例子,這里提出要點(diǎn):
- 繼承RecyclerView.Adapter<T>
- 實(shí)現(xiàn)繼承的方法。
- 利用onCreateViewHolder方法創(chuàng)建ViewHolder
- 利用onBindViewHolder方法顯示具體內(nèi)容
- 利用getItemCount總計(jì)數(shù)據(jù)的總數(shù)
public class MyAdapter extends RecyclerView.Adapter<ItemHolder> {
private LayoutInflater mInflater;
private List<InfoBean> datas;
public MyAdapter(Context mContext, List<InfoBean> datas) {
this.datas = datas;
mInflater = LayoutInflater.from(mContext);
}
@Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = mInflater.inflate(R.layout.item_list,parent,false);
ItemHolder itemHolder = new ItemHolder(v);
return itemHolder;
}
@Override
public void onBindViewHolder(ItemHolder holder, int position) {
holder.imageView.setImageResource(datas.get(position).getId());
holder.teTitle.setText(datas.get(position).getTitle());
holder.teContent.setText(datas.get(position).getContent());
}
@Override
public int getItemCount() {
return datas.size();
}
}
4.創(chuàng)建item布局和主布局
這一點(diǎn)比較簡(jiǎn)單,不做解釋
- 在主界面顯示recyclerView
這一點(diǎn)同普通的listView實(shí)現(xiàn)基本相同,有一點(diǎn)需要注意的是:在顯示之前需要為recyclerVIew設(shè)置布局。
關(guān)鍵代碼如下:
RecyclerView.LayoutManager mManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mManager);
基本上到這里,就差不多完成了。
代碼下載