自定义ListView的适配器,抽取基类,简单实现

xiaoxiao2021-02-28  6

1、把listView的适配器抽取变成一个基类,这样的话,就不用再适配

package com.example.administrator.adapter.baseAdapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.List; public abstract class CommonAdapter<T> extends BaseAdapter { protected List<T> list; protected Context context; private int layoutId; public CommonAdapter(Context context, List<T> list, int layoutId) { this.list = list; this.context = context; this.layoutId = layoutId; } @Override public int getCount() { if (list == null) { return 0; } return list.size(); } @Override public Object getItem(int position) { if (list == null) { return null; } return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = ViewHolder.get(context, convertView, layoutId); convert(holder, position); return holder.getConvertView(); } public abstract void convert(ViewHolder holder, int position); }

2、再把ViewHolder重新编写:

package com.example.administrator.adapter.baseAdapter; import android.content.Context; import android.util.SparseArray; import android.view.View; public class ViewHolder { private SparseArray<View> views; // private Map<Integer, View> views; private View mConvertView; public ViewHolder(Context context, int layoutId) { views = new SparseArray<>(); if (mConvertView == null) { mConvertView = View.inflate(context, layoutId, null); mConvertView.setTag(this); } } public static ViewHolder get(Context context, View convertView, int layoutId) { if (convertView == null) { return new ViewHolder(context, layoutId); } return (ViewHolder) convertView.getTag(); } public <T extends View> T getView(int resId) { View view = views.get(resId); if (view == null) { view = mConvertView.findViewById(resId); views.put(resId, view); } return (T) views.get(resId); } public View getConvertView() { return mConvertView; } }

简单的调用:

package com.example.administrator.adapter; import android.content.Context; import android.view.View; import com.example.administrator.R; import com.example.administrator.adapter.baseAdapter.CommonAdapter; import com.example.administrator.adapter.baseAdapter.ViewHolder; import com.mikepenz.iconics.view.IconicsTextView; import java.util.List; public class MenuAdapter extends CommonAdapter<String> { public MenuAdapter(Context context, List<String> list, int layoutId) { super(context, list, layoutId); } @Override public void convert(ViewHolder holder, int position) { IconicsTextView menuIcon = holder.getView(R.id.menu_icon); menuIcon.setText(list.get(position)); } }
转载请注明原文地址: https://www.6miu.com/read-2000158.html

最新回复(0)