Android 中BaseAdapter 与ButterKinf
2020-10-23 本文已影响0人
飞指
package com.zhiteng.base.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidx.annotation.LayoutRes;
import java.util.List;
import butterknife.ButterKnife;
/**
* Adapter 基类封装
*/
public abstract class CustomAdapter extends BaseAdapter {
protected String TAG = CustomAdapter.class.getSimpleName();
private Context context;
private List<?> list;
private int layoutId;
public CustomAdapter(Context context, List<?> list) {
this.context = context;
this.list = list;
}
public void setLayoutId(int layoutId) {
this.layoutId = layoutId;
}
/**
* 构造函数
*
* @param context 上下文
* @param list 需要展示的数据列表
* @param layoutId 布局文件ID
*/
public CustomAdapter(Context context, List<?> list, @LayoutRes int layoutId) {
this(context, list);
this.layoutId = layoutId;
}
/**
* 设置数据
*
* @param list
*/
public void setNewList(List<?> list) {
this.list = list;
notifyDataSetChanged();
}
/**
* 获取当前Adapter 中的数据
*
* @return
*/
public List<?> getData() {
return list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (layoutId == 0) {
throw new NullPointerException("当前未初始化布局,请初始化布局,layoutId is Error");
}
BaseViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(layoutId, null, false);
viewHolder = getViewHolder();
viewHolder.setView(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (BaseViewHolder) convertView.getTag();
}
setViewOnData(getItem(position), viewHolder);
return convertView;
}
protected abstract void setViewOnData(Object bean, BaseViewHolder baseViewHolder);
private ChildClickListener childClickListener;
public void setChildClickListener(ChildClickListener childClickListener) {
this.childClickListener = childClickListener;
}
protected abstract BaseViewHolder getViewHolder();
interface ChildClickListener {
void itemChildClick(int position, int resId);
}
public class BaseViewHolder {
public void setView(View view) {
ButterKnife.bind(this, view);
}
}
}