RecyclerView通过名称可以看出,是可以复用的view。官方对其解释为:可以在有限的窗口展示大量的数据集。其实类似的控件我们也了解很多,比如ListView,GridView.然而RecyclerView更专注于复用,也更加的灵活。下面我们就一起走进RecyclerView的世界。
基本用法
使用RecyclerView必须导入support-v7包,与ListView不相同的是,需要设置布局管理器LayoutManager,下面就分别介绍LinearLayoutManager,GirdLayoutManager,StaggeredGridLayoutManager,实现ListView,GirdView,瀑布流。
首先看listview列表的实现。
MyAdapter adapter = new MyAdapter(this, initData());
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//设置布局管理器LayoutManager()
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//设置adapter
recyclerView.setAdapter(adapter);
//初始化数据
private ArrayList initData() {
ArrayList lists = new ArrayList();
for (int i = 0; i <= 100; i++) {
lists.add(i);
}
return lists;
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList arrayList;
private Context context;
public MyAdapter(Context context, ArrayList arrayList) {
this.arrayList = arrayList;
this.context = context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_recyclerview_text, parent, false));
return myViewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.textView.setText(arrayList.get(position) + "");
}
@Override
public int getItemCount() {
return arrayList.size();
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
}
}