RecyclerView适配器的封装

RecyclerView适配器基类的封装

RecyclerView.Adapter封装类

public abstract class AutoRollAdapter extends RecyclerView.Adapter {

protected List ts = new ArrayList<>();

public List getData() {
    return ts;
}
public int size() {
    return null == ts ? 0 : ts.size();
}

public void add(T t) {
    ts.add(t);
    notifyDataSetChanged();
}

protected void remove(int index) {
    ts.remove(index);
    notifyDataSetChanged();
}

public void addAll(List ts) {
    this.ts.addAll(ts);
    notifyDataSetChanged();
}

public void clear() {
    this.ts.clear();
    notifyDataSetChanged();
}

@LayoutRes
public abstract int getLayoutResId();

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ViewHolder(parent, getLayoutResId());
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    if (size() > 0) {
        onConvert(holder, getItem(position));
      
       // onConvert(holder, getItem(position), position);
    }
}

protected abstract void onConvert(ViewHolder holder, T bean);

 //返回条目索引,根据自己需求设置返回参数
protected abstract void onConvert(ViewHolder holder, T bean, int position);

public T getItem(int position) {
    return ts.get(position % size());
}
}

ViewHolder封装

public class ViewHolder extends RecyclerView.ViewHolder {
private SparseArray viewArray;

public ViewHolder(ViewGroup parent, @LayoutRes int resId) {
    super(LayoutInflater.from(parent.getContext()).inflate(resId, parent, false));
    viewArray = new SparseArray<>();
}

public  T findViewById(@IdRes int resId) {
    View view = viewArray.get(resId);
    if(view == null) {
        view = itemView.findViewById(resId);
        viewArray.put(resId, view);
    }
    return (T) view;
}

public ViewHolder setText(@IdRes int resId, CharSequence text) {
    TextView tv = findViewById(resId);
    if(tv != null) {
        tv.setText(text);
    }
    return this;
}

public ViewHolder setTextColor(@IdRes int resId, int color) {
    TextView tv = findViewById(resId);
    if(tv != null) {
        tv.setTextColor(color);
    }
    return this;
}
public ViewHolder setOnClickListener(int viewId, View.OnClickListener onClickListener) {
    View view = findViewById(viewId);
    view.setOnClickListener(onClickListener);
    return this;
}
}

ViewHolder进行了封装目前之封装了setText、setTextColor以及setOnClickListener,可以根据自己的需求进行添加

使用封装的基类

public class CallAdapter extends AutoRollAdapter {

//设置布局-
@Override
public int getLayoutResId() {
    return R.layout.listview_item_call;
}

//设置控件属性
@Override
protected void onConvert(ViewHolder holder, CallBean bean) {
    holder.setText(R.id.tv_window, bean.getWindowName())
            .setTextColor(R.id.tv_window, bean.getStateColor());
}
}

你可能感兴趣的:(进阶,android,android,studio,android-studio)