我使用 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 存储库中找到完整代码:Recyclerview-通用适配器 https://github.com/ravirupareliya/Recyclerview-Generic-Adapter
问题我面临的是使用通用适配器后RecyclerView
加载时间增加,有一秒钟它显示设计时布局,然后加载原始数据。
你缺少的部分是binding.executePendingBindings()
in bindData
:
public void bindData(T model) {
bindingInterface.bindData(binding, model);
binding.executePendingBindings();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)