RecycleView 我们在Android项目中经常使用,adapter一般我们是这么写的:显示新建一个Adapter类继承 RecyclerView.Adapter,然后
再写一个ViewHolder类继承RecyclerView.ViewHolder类
class JcActivityListAdapter(context: Context, list: List<JCActivityBean>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var context = context
var list = list
lateinit var disposable: Disposable
override fun getItemViewType(position: Int): Int {
return if (position == 0) {
ActivityConstant.TYPE_HEADER_VIEW
} else {
ActivityConstant.TYPE_NORMAL_VIEW
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
if (viewType == ActivityConstant.TYPE_HEADER_VIEW) {
var headView = LayoutInflater.from(context).inflate(R.layout.group_buy_activity_head_layout, parent, false)
return HeaderHolder(headView)
} else {
var view = LayoutInflater.from(context).inflate(R.layout.jc_activity_list_item_layout, parent, false)
return ListHolder(view)
}
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
...........省略业务代码
}
inner class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var image = itemView.findViewById(R.id.image) as SimpleDraweeView
...........省略业务代码
}
inner class HeaderHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
}
这样的话,我们就会发现每次都要新建一个ViewHolder继承 RecyclerView.ViewHolder的匿名内部类,很是繁琐,
我们可以写一个公共ViewHolder类,把布局文件作为参数传进去 代码如下:
public class CustomViewHolder extends RecyclerView.ViewHolder {
private SparseArray<View> views;
private View rootView;
public CustomViewHolder(View itemView) {
super(itemView);
views = new SparseArray<>();
this.rootView = itemView;
}
public static CustomViewHolder createViewHolder(Context context, ViewGroup parent, int resource) {
View rootView = LayoutInflater.from(context).inflate(resource, parent, false);
CustomViewHolder customViewHolder = new CustomViewHolder(rootView);
return customViewHolder;
}
public View getRootView() {
return rootView;
}
public <T extends View> T getView(int resource) {
View view = views.get(resource);
if (view == null) {
view = rootView.findViewById(resource);
views.put(resource, view);
}
return (T) view;
}
}
使用方式如下:
class DcGoodsListAdapter(context: Context,list: MutableList<CommdityBean>): RecyclerView.Adapter<CustomViewHolder>() {
var context = context
var list = list
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CustomViewHolder {
return CustomViewHolder.createViewHolder(parent?.context,parent, R.layout.dc_goods_item_layout)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: CustomViewHolder?, position: Int) {
(holder?.getView(R.id.commodity_name)as TextView).text = list[position].commodity_name
//业务代码省略
}
}
网友评论