SimpleAdapter是适配器中扩展性最好的,但是如果用simpleAdapter添加按钮,为按钮添加响应事件很难做到。为此我们可以继承simpleAdapter,自己实现响应事件。
示例如下:
private class MySimpleAdapter extends SimpleAdapter {
public MySimpleAdapter(Context context,
List<? extends Map<String, ?>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final int mPosition = position;
convertView = super.getView(position, convertView, parent);
Button buttonAdd = (Button) convertView
.findViewById(R.id.button_add);// id为你自定义布局中按钮的id
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.obtainMessage(BUTTON_ADD, mPosition, 0)
.sendToTarget();
}
});
Button buttonDelete = (Button) convertView
.findViewById(R.id.button_delete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.obtainMessage(BUTTON_DELETE, mPosition, 0)
.sendToTarget();
}
});
return convertView;
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case BUTTON_ADD:
HashMap<String, Object> map = new HashMap<String, Object>();
mList.add(map);
notifyDataSetChanged();// 这个函数很重要,告诉Listview适配器数据发生了变化
mShowInfo.setText("你点击了第" + (msg.arg1 + 1) + "按钮");
break;
case BUTTON_DELETE:
mList.remove(msg.arg1);
notifyDataSetChanged();
mShowInfo.setText("你删除了第" + (msg.arg1 + 1) + "行");
break;
}
}
};
}