RecyclerView generic adapter with DataBinding

大兔子大兔子 提交于 2020-01-02 04:37:07

问题


I have created generic adapter for RecyclerView by using DataBinding. Here is small code snippet

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();
}
}

You can find full code in Github repo : Recyclerview-Generic-Adapter

The problem i am facing is after using generic adapter RecyclerView loading time increase and for a second it shows design time layout and than loads original data.


回答1:


The piece you're missing is the binding.executePendingBindings() in bindData:

public void bindData(T model) {
    bindingInterface.bindData(binding, model);
    binding.executePendingBindings();
}


来源:https://stackoverflow.com/questions/40588085/recyclerview-generic-adapter-with-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!