RecylerView是support-v7包中的新组件,可以替代ListView
基本使用:
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this );
//设置布局管理器
recyclerView.setLayoutManager(layoutManager);
//设置为垂直布局,这也是默认的
layoutManager.setOrientation(OrientationHelper. VERTICAL);
//设置Adapter
recyclerView.setAdapter( recycleAdapter);
//设置分隔线
recyclerView.addItemDecoration( new DividerGridItemDecoration(this ));
//设置增加或删除条目的动画
recyclerView.setItemAnimator( new DefaultItemAnimator());
适配器:
要实现的方法:
//等同于BaseAdapter的getCount();
@Override
public int getItemCount() {
return topics.size();
}
//相当于把BaseAdapter的getView()分成两个方法:创建holder和绑定数据的方法
//创建viewHolder的方法:其中的viewType就是getItemViewType()
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(),R.layout.item_type_1,null);
return new MyViewHolder(view);
}
//绑定viewHolder的方法:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//设置数据
//设置图片的点击事件
}
//自定义一个viewHolder
public static class MyViewHolder extends RecyclerView.ViewHolder{
@InjectView(R.id.userPhoto)
CircleImageView userPhoto;
@InjectView(R.id.userId)
TextView userId;
@InjectView(R.id.isVip)
ImageView isVip;
@InjectView(R.id.sex)
ImageView sex;
@InjectView(R.id.isYearVip)
ImageView isYearVip;
@InjectView(R.id.createDate)
TextView createDate;
@InjectView(R.id.title)
TextView title;
@InjectView(R.id.content)
TextView content;
@InjectView(R.id.resource)
ImageView resource;
@InjectView(R.id.distance)
TextView distance;
public MyViewHolder(View itemView) {
super(itemView);
//构造中传进来的就是被复用的条目,可以用来完成findViewById的操作
ButterKnife.inject(this,itemView);
}
}