基本使用
在 build.gradle 文件中引入該類。
compile 'com.android.support:recyclerview-v7:23.4.0'
必要的初始化
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
/設(shè)置布局管理器
mRecyclerView.setLayoutManager(mLayoutManager);
// 設(shè)置adapter
mRecyclerView.setAdapter(mAdapter);
// 設(shè)置Item添加和移除的動畫
mRecyclerView.setItemAnimator(newDefaultItemAnimator());
// 設(shè)置Item之間間隔樣式
mRecyclerView.addItemDecoration(mDividerItemDecoration);
RecyclerView 提供了三種布局管理器:
LinerLayoutManager 以垂直或者水平列表方式展示 Item
GridLayoutManager 以網(wǎng)格方式展示 Item
StaggeredGridLayoutManager 以瀑布流方式展示 Item
RecyclerView 適配器 Adapter 代碼
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private ArrayList<String> mData;
public MyAdapter(ArrayList<String> data) {
this.mData = data;
}
public void updateData(ArrayList<String> data) {
this.mData = data;
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// 實例化展示的view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_rv_item, parent, false);
// 實例化viewholder
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// 綁定數(shù)據(jù)
holder.mTv.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView mTv;
public ViewHolder(View itemView) {
super(itemView);
mTv = (TextView) itemView.findViewById(R.id.item_tv);
}
}
}