1.加入依赖
dependencies {
compile 'com.android.support:recyclerview-v7:21.0.+'
}
2.在activity中获取RecyclerView控件,并设置相关参数和适配器
RecyclerView rv = findViewById(R.id.rv);
string = new String[10];
for (int i = 0; i < string.length; i++) {
string[i] = "item " + i;
}
//创建线性layoutmanager
linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
//如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
rv.setHasFixedSize(true);
RecyclerAdapter adapter = new RecyclerAdapter(string);
rv.setAdapter(adapter);
3.创建适配器
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private String string[];
public RecyclerAdapter(String string[]) {
this.string = string;
}
/**
* 创建新的view,被layoutmanager所调用
*
* @param parent
* @param viewType
* @return
*/
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
/**
* 将数据与界面进行绑定
*
* @param holder
* @param position
*/
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.textView.setText(string[position]);
}
/**
* 获取数据的数量
*
* @return
*/
@Override
public int getItemCount() {
return string.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.item);
}
}
}
横向布局
如果想要一个横向的List只要设置LinearLayoutManager如下就行,注意要声明mLayoutManager的类型是LinearLayoutManager而不是父类LayoutManager:
linearLayoutManager .setOrientation(LinearLayoutManager.HORIZONTAL);
Grid布局
如果想要一个Grid布局的列表,只要声明LayoutManager为GridLayoutManager即可:
mLayoutManager = new GridLayoutManager(context,columNum);
mRecyclerView.setLayoutManager(mLayoutManager);
注意,在Grid布局中也可以设置列表的Orientation属性,来实现横向和纵向的Grid布局。
瀑布流布局
瀑布流就使用StaggeredGridLayoutManager吧,具体方法与上面类似,就不做介绍啦。