2
データバインディングを持つジェネリックrecyclerviewアダプタ:アンドロイド:私は以下のように一般的なRecyclerviewアダプタを作成しようとしました
BaseRecyclerAdapter:
public class BaseRecyclerAdapter<T, MVH extends BaseViewHolder<T>, EVH extends BaseViewHolder<T>> extends RecyclerView.Adapter<BaseViewHolder<T>> {
private static final int VIEW_TYPE_EMPTY = 0;
private static final int VIEW_TYPE_DATA = 1;
private List<T> list = new ArrayList<>();
@LayoutRes
private int emptyViewLayoutResource;
private Class<EVH> emptyViewHolder;
@LayoutRes
private int dataLayoutResource;
private Class<MVH> dataViewHolder;
public BaseRecyclerAdapter(int emptyViewLayoutResource, Class<EVH> emptyViewHolder, int dataLayoutResource, Class<MVH> dataViewHolder) {
this.emptyViewLayoutResource = emptyViewLayoutResource;
this.emptyViewHolder = emptyViewHolder;
this.dataLayoutResource = dataLayoutResource;
this.dataViewHolder = dataViewHolder;
}
@Override
public BaseViewHolder<T> onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
ViewDataBinding binding = DataBindingUtil.inflate(layoutInflater, viewType == VIEW_TYPE_EMPTY ? emptyViewLayoutResource : dataLayoutResource, parent, false);
try {
return viewType == VIEW_TYPE_EMPTY ? emptyViewHolder.getConstructor(ViewDataBinding.class).newInstance(binding) : dataViewHolder.getConstructor(View.class).newInstance(binding);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void onBindViewHolder(BaseViewHolder<T> holder, int position) {
int viewType = getItemViewType(position);
if (viewType == VIEW_TYPE_EMPTY) {
} else {
holder.bind(list.get(position));
}
}
@Override
public int getItemCount() {
return list.size() == 0 ? 1 : list.size();
}
@Override
public int getItemViewType(int position) {
return list.size() == 0 ? VIEW_TYPE_EMPTY : VIEW_TYPE_DATA;
}
}
BaseViewHolder:
public class BaseViewHolder<T> extends RecyclerView.ViewHolder {
private final ViewDataBinding binding;
public BaseViewHolder(ViewDataBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(T t) {
binding.setVariable(BR.obj, t);
binding.executePendingBindings();
}
}
缶誰もがこれを試して、私にこのクラスを初期化してReでそれを使う方法を教えてくださいcyclerView?
[こちら](https://github.com/ravirupareliya/Recyclerview-Generic-Adapter)をチェックしてください。 –