android——RecyclerView通用适配器
ExecFunction编程式接口
public interface ExecFunction {
public void exec(Object data, View view);
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
/**
* 抽离出不同点
* 1. 执行上下文
* 2. RecyclerView实例
* 3. 数据源
* 4. 子项视图
* 5. 绑定方法
*/
private List dataResource; // 数据源
private int layoutId ; // 视图资源
private ExecFunction function; // 数据视图绑定
private int len = -1; // 子项渲染个数,-1代表所有
public RecyclerView view; // RecyclerView实例,公共成员变量
/**
* @param activity 渲染RecyclerView所在的Activity实例
* @param resourceId RecyclerView组件id
* @param dataResource 数据源
* @param layoutId 布局id
* @param function 回调方法用于数据与视图的绑定
*/
public MyAdapter(AppCompatActivity activity, int resourceId, List dataResource, int layoutId, ExecFunction function){
this.dataResource = dataResource;
this.layoutId = layoutId;
this.function = function;
this.view = (RecyclerView)activity.findViewById(resourceId);
this.view.setAdapter(this);
}
public void setLength(int length){
this.len = length;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(layoutId,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
View view = holder.getView();
function.exec(dataResource.get(position),view);
}
@Override
public int getItemCount() {
if(this.len>0){
return this.len;
}else if(this.len==0){
throw new RuntimeException("The length must not be 0");
}
return dataResource.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private View view = null;
public ViewHolder(@NonNull View itemView) {
super(itemView);
this.view = itemView;
}
public View getView(){
return view;
}
}
}
使用示例:
MyAdapter adapter = new MyAdapter(this,R.id.recycle_list,list, R.layout.test_view, new ExecFunction() {
@Override
public void exec(Object data, View view) {
final TestBean d = (TestBean) (data);
TextView title = (TextView)view.findViewById(R.id.test_title);
TextView content = (TextView)view.findViewById(R.id.test_content);
content.setText(d.name);
title.setText(String.valueOf(d.age));
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast t = Toast.makeText(this,"点击了"+d.name, Toast.LENGTH_SHORT);
t.show();
}
});
}
});
adapter.setLength(12);
adapter.view.setLayoutManager(new GridLayoutManager(this,4));
本文来自博客园,作者:maplerain,转载请注明原文链接:https://www.cnblogs.com/maplerain/p/16688829.html 博主B站