我使用DataBinding为RecyclerView创建了通用适配器。这是一个小代码片段
public class RecyclerAdapter<T, VM extends ViewDataBinding> extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private final Context context;
private ArrayList<T> items;
private int layoutId;
private RecyclerCallback<VM, T> bindingInterface;
public RecyclerAdapter(Context context, ArrayList<T> items, int layoutId, RecyclerCallback<VM, T> bindingInterface) {
this.items = items;
this.context = context;
this.layoutId = layoutId;
this.bindingInterface = bindingInterface;
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
VM binding;
public RecyclerViewHolder(View view) {
super(view);
binding = DataBindingUtil.bind(view);
}
public void bindData(T model) {
bindingInterface.bindData(binding, model);
}
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(layoutId, parent, false);
return new RecyclerViewHolder(v);
}
@Override
public void onBindViewHolder(RecyclerAdapter.RecyclerViewHolder holder, int position) {
T item = items.get(position);
holder.bindData(item);
}
@Override
public int getItemCount() {
if (items == null) {
return 0;
}
return items.size();
}
}
您可以在Github repo中找到完整代码:Recyclerview-Generic-Adapter
我面临的问题是在使用通用适配器RecyclerView
加载时间增加后,它会显示设计时间布局,而不是加载原始数据。
答案 0 :(得分:3)
您遗失的内容是binding.executePendingBindings()
中的bindData
:
public void bindData(T model) {
bindingInterface.bindData(binding, model);
binding.executePendingBindings();
}