懒人ListView适配器
适配器
public abstract class CommonAdaper<T> extends BaseAdapter {
private Context context;
private List<T> list;
public CommonAdaper(Context context, List<T> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list == null ? 0 : list.size();
}
@Override
public T getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = ViewHolder.get(view, viewGroup, 列表子项布局的id, i);
convert(holder, getItem(i));
return holder.getConvertView();
}
public abstract void convert(ViewHolder holder, T item);
}
ViewHolder【这个是核心:不变的在CommonAdaper,变得在ViewHolder】
public class ViewHolder {
//现在对于int作为键的官方推荐用SparseArray替代HashMap
private final SparseArray<View> views;
private int position;
private View convertView;
private Context context;
private ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
this.context = context;
this.views = new SparseArray<>();
this.convertView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
convertView.setTag(this);
}
/**
* 拿到一个ViewHolder对象
*/
public static ViewHolder get(View convertView, ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
return new ViewHolder(parent.getContext(), parent, layoutId, position);
}
return (ViewHolder) convertView.getTag();
}
/**
* 通过控件的Id获取对于的控件,如果没有则加入views
*/
public <T extends View> T getView(int viewId) {
View view = views.get(viewId);
if (view == null) {
view = convertView.findViewById(viewId);
views.put(viewId, view);
}
return (T) view;
}
public View getConvertView() {
return convertView;
}
/**
* 设置字符串
*/
public ViewHolder setText(int viewId, String text) {
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
/**
* 设置图片
*/
public ViewHolder setImageResource(int viewId, int drawableId) {
ImageView iv = getView(viewId);
iv.setImageResource(drawableId);
return this;
}
/**
* 设置图片
*/
public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
ImageView iv = getView(viewId);
iv.setImageBitmap(bitmap);
return this;
}
public int getPosition() {
return position;
}
}
Activity中调用【结合你的实际需求写】
public class XXActivity extends Activity {
//声明控件
private ListView listView;
//声明数据
private List<实体类> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_school);
listView = (ListView) findViewById(列表对应的id);
initList();
listView.setAdapter(new CommonAdaper<实体类>(this, list) {
@Override
public void convert(ViewHolder holder, SchoolData item) {
holder.setText(列表子项的TextView对应的的id, item.getName());
holder.setImageResource(列表子项ImageView对应的id, item.getImg_id());
}
});
}
private void initList() {
list = new ArrayList<实体类>();
for (int i = 0; i < 10; i++) {
list.add(new SchoolData());
}
}
}
布局就不写了,你能收到说明你的前面的工作应该没问题(相信你)!!