RecyclerView 介绍 01
2015-02-27 18:17 HalZhang 阅读(911) 评论(1) 编辑 收藏 举报RecyclerView是Android support v7里面是一个自定义控件。用来显示大量数据集合。类似ListView和GridView这两个控件,RecyclerView同样可以实现,甚至更好。
以前我们在实现ListView和GridView的时候,都会定义一个ViewHolder用于优化UI性能【详见】,RecycleView的实现,已经是自带ViewHolder的实现。请看示例。
-
实现Adapter,定义每个Item的布局UI和数据。
-
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
-
-
private List<String> mDatas = new ArrayList<>(0);
-
-
public MyRecyclerAdapter(List<String> datas) {
-
if (datas != null) {
-
mDatas.addAll(datas);
-
}
-
}
-
-
public static final class ViewHolder extends RecyclerView.ViewHolder {
-
-
private final TextView textView;
-
private final Button button;
-
-
-
public ViewHolder(View itemView) {
-
super(itemView);
-
textView = (TextView) itemView.findViewById(R.id.item_text);
-
button = (Button) itemView.findViewById(R.id.item_button);
-
button.setOnClickListener(new View.OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
Toast.makeText(v.getContext(), String.valueOf(getPosition()), Toast.LENGTH_SHORT).show();
-
}
-
});
-
}
-
-
public TextView getTextView() {
-
return textView;
-
}
-
-
public Button getButton() {
-
return button;
-
}
-
}
-
-
@Override
-
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
-
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
-
return new ViewHolder(view);
-
}
-
-
@Override
-
public void onBindViewHolder(ViewHolder holder, int position) {
-
holder.getButton().setText(String.valueOf(position));
-
holder.getTextView().setText(mDatas.get(position));
-
}
-
-
@Override
-
public int getItemCount() {
-
return mDatas.size();
-
}
-
-
}
-
-
初始化RecyclerView
设置Adapter和LayoutManager。LayoutManager定义了每个Item的排列形式。官方提供两种实现,LinearLayoutManager和GridLayoutManager,当然我们也可以根据需求,自己实现LayoutManager。
-
recyclerView = (RecyclerView) findViewById(R.id.recycler);
-
MyRecyclerAdapter adapter = new MyRecyclerAdapter(Datas.getDatas(1000));
-
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
-
recyclerView.setLayoutManager(layoutManager);
-
recyclerView.setAdapter(adapter);
-
RecyclerView就是这么简单。
源码:GitHub