项目开发中会涉及到很多列表的页面。如果每个页面都写一个adapter,我们估计会疯掉。我现在的目的就是在保证质量的同时要写更少的代码。所以,封装呗。
recyclerview有自己的adapter和视图管理。我们只需要把实例化时要传入的参数泛型抽象,对不同的view实现不同的获取与设置内容的方法即可。
Adapter:
abstract public class RecyclerViewAdapter<T> extends RecyclerView.Adapter {
protected List<T> list;
private Integer itemView;//布局id
protected View.OnClickListener onClickListener;
protected Context mContext;
public RecyclerViewAdapter(Context mContext ,List<T> list, Integer itemView) {
this.list = list;
this.itemView = itemView;
this.mContext = mContext;
}
public RecyclerViewAdapter(List<T> list, int itemView) {
this.list = list;
this.itemView = itemView;
}
public void setOnClickListener(View.OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
abstract public RecyclerView.ViewHolder onCreateViewHolder(View itemView, int viewType);
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
view = LayoutInflater.from(parent.getContext()).inflate(itemView, parent, false);
return onCreateViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyViewHolder viewHolder = (MyViewHolder) holder;
if (list != null) {
viewHolder.bind(position ,list.get(position));
viewHolder.bind(position);
}
}
@Override
public int getItemCount() {
return list.size();
}
//文本相关
public void setText(TextView text, Object object) {
String content = String.valueOf(object);
if (TextUtils.isEmpty(content) || content.equals("null")) {
text.setText("");
} else {
text.setText(content);
}
}
//图片相关
public void setImage(ImageView imageView, String imagePath, int width, int height) {
if (TextUtils.isEmpty(imagePath)) {
imagePath = "http";
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(imageView.getContext())
.load(imagePath).resize(width, height)
.centerCrop()
.placeholder(R.mipmap.default_error)
.into(imageView);
}
}
MyViewHolder:
abstract public class MyViewHolder<T> extends RecyclerView.ViewHolder{
public MyViewHolder(View itemView) {
super(itemView);
}
public void bind(int position){
}
public void bind(int position ,T item){
}
}