반응형

매번 사용하는 BaseActivity , Fragment 

음.. 생각해보니 Adapter를 만들생각을 안해봄..그래서 만들었다.  ( 딱히 공통으로 들어갈만한게 없어도 이긴한데..ㅋ  )

 

 

1. BaseAdapter 

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

 

https://github.com/ShinHoChull/MVVM/tree/master/app/src/main/java/com/m2comm/test/base

 

GitHub - ShinHoChull/MVVM: MVVM Test

MVVM Test. Contribute to ShinHoChull/MVVM development by creating an account on GitHub.

github.com

 

반응형

+ Recent posts