- bindtViewHolder 메서드는 onCreateViewHolder에서 B 타입으로 넘겨줘야하는데 딱히 방법이 생각나지 않았다..ㅠ
public abstract class BaseAdapter<
A extends ViewDataBinding,
B extends RecyclerView.ViewHolder
>
extends RecyclerView.Adapter<B> {
protected abstract @LayoutRes
int getLayout();
protected abstract B bindViewHolder(A binding);
@NonNull
@Override
public B onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
A binding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext())
, getLayout(), parent
, false);
return bindViewHolder(binding);
}
}
2. BaseViewHolder
abstract public class BaseViewHolder<
A extends ViewDataBinding
>
extends RecyclerView.ViewHolder {
protected A mBinding;
public BaseViewHolder(A a) {
super(a.getRoot());
mBinding = a;
}
}
--------------사용 -------
1. Adapter
- 확실히 사용이 간결해졌다.
public class MainAdapter
extends BaseAdapter<
ItemTextBinding
, MainViewHolder
> {
private final ArrayList<String> mArr;
public MainAdapter(ArrayList<String> mArr) {
this.mArr = mArr;
}
@Override
protected int getLayout() {
return R.layout.item_text;
}
@Override
protected MainViewHolder getViewHolder(ItemTextBinding binding) {
return new MainViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
holder.bind(mArr.get(position));
}
@Override
public int getItemCount() {
return mArr.size();
}
}
2. ViewHolder
public class MainViewHolder
extends BaseViewHolder<ItemTextBinding> {
public MainViewHolder(ItemTextBinding itemTextBinding) {
super(itemTextBinding);
}
public void bind(String row) {
mBinding.fragTextview.setText(row);
}
}