1、环境
在build.gradle里
compile 'com.android.support:recyclerview-v7:25.+'
2、类比ListView来看RecyclerView的用法
首先,关键的三点:子项布局,数据类,Adapter中,前两项不用动,依旧只看第三点Adapter。
类比ListView的getView()
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;//在FruitAdapter的构造函数里,获得子项布局资源
public FruitAdapter(Context context, int resource, List<Fruit> objects) {
super(context, resource, objects);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position); //获得数据实例
View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false); //获得子项布局资源
ImageView imageView = (ImageView)view.findViewById(R.id.image_view); 子项布局资源中的控件
TextView textView = (TextView)view.findViewById(R.id.text_view); 子项布局资源中的控件
imageView.setImageResource(fruit.getImageId()); 添加
textView.setText(fruit.getName()); 添加
return view;
}
}
RecyclerView这里将功能拆开来放:
获得子项布局资源,在onCreate方法里(返回holder)
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
获得子项布局资源的控件,在内部类ViewHoler的构造方法里
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView;
public ViewHolder(View view){
super(view);
imageView = (ImageView)view.findViewById(R.id.image_view);
textView = (TextView)view.findViewById(R.id.text_view);
}
}
将布局资源的控件与数据绑定,在onBind方法里
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Fruit fruit = mFruitList.get(position);
holder.imageView.setImageResource(fruit.getImageId());
holder.textView.setText(fruit.getName());
}
哦,对了,数据源要通过Adapter的构造函数传入。区别于ListView的那种Adapter的构造函数需要三个参数(上下文,子项布局,数据)
private List<Fruit> mFruitList;
public FruitAdapter(List<Fruit> fruitList){
mFruitList = fruitList;
}
在MainActivity里
initFruitList();
FruitAdapter adapter = new FruitAdapter(fruitList);//参数变了~只需要传入数据,其他的Adapter都做好了
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);//LayoutManager
recyclerView.setLayoutManager(layoutManager);//LayoutManager
recyclerView.setAdapter(adapter);
3、RecyclerView的点击事件
在onCreate方法里写
- 可以实现对子项布局中的某个控件
获取数据实例:
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
- 也能实现对整个子项布局实现监听。
给ViewHolder的构造方法添加一个View myView,并myView = view就可以直接在onCreate方法里对它监听了,这时就是对整个子项布局的监听。