1.引入依赖包
compile 'com.android.support:recyclerview-v7:23.0.1'
2.main.xml添加recyclerView
<android.support.v7.widget.RecyclerView
android:id="@+id/mainRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3.新建recyclerview子项目布局
layout目录新建item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/banjinImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/banjinText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
4.新建数据源类型
//数据源类文件
public class Banjin
{
private String name;
private int imageId;
public Banjin(String name ,int imageId)
{
this.name=name;
this.imageId = imageId;
}
public String getName()
{
return name;
}
public int getImageId()
{
return imageId;
}
5.新建适配器类
public class BanjinAdapter extends RecyclerView.Adapter<BanjinAdapter.ViewHolder>
{
//数据源成员
private List<Banjin> mBanjinList;
//构造函数导入数据
public BanjinAdapter(List<Banjin> mBanjinList)
{
this.mBanjinList = mBanjinList;
}
//定义ViewHolder类
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView banjinImage;
TextView banjinText;
public ViewHolder(View view){
super(view);
banjinText=(TextView)view.findViewById(R.id.banjinText);
banjinImage=(ImageView)view.findViewById(R.id.banjinImage);
}
}
//创建ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{ //子项目布局xml实例化,返回view
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.banjin_xml,parent,false);
ViewHolder viewHolder=new ViewHolder(view);
return viewHolder;
}
//返回数据实现
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position)
{ //返回mBanjinList此位置的数据
Banjin banjin=mBanjinList.get(position);
//设置数据
viewHolder.banjinText.setText(banjin.getName());
viewHolder.banjinImage.setImageResource(banjin.getImageId());
}
@Override
public int getItemCount()
{
// 返回mBanjinList总数
return mBanjinList.size();
}
}
6.Activity代码初始化
private List<Banjin> banjinList;
oncreate()方法
//初始化banjinLlist数据
initBanjinList();
//返回recycleview实例
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.mainRecyclerView);
//设置recyclerviw布局管理器
GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(layoutManager);
//设置recyclerview适配器
BanjinAdapter banjinAdapter=new BanjinAdapter(banjinList);
recyclerView.setAdapter(banjinAdapter);
initBanjinList()初始化数据源实现
private void initBanjinList(){
banjinList=new ArrayList<>();
Banjin xieJieYuanGuan=new Banjin("斜切圆管",R.drawable.bj_xjyt);
banjinList.add(xieJieYuanGuan);
Banjin liangJieWanTou=new Banjin("两节弯头",R.drawable.bj_djwt);
banjinList.add(liangJieWanTou);
Banjin duoJieYuanGuan=new Banjin("多节弯头",R.drawable.bj_djwt);
banjinList.add(duoJieYuanGuan);
}
fd