标签:android
SimpleAdapter是四个适配器里最重要的适配器,它不仅实现了数据的绑定,而且可以自定义控件。
在自定义控件时,如果使用了按钮、复选框、单选框等需要点击监听器的控件,就得重写SimpleAdapter的getView函数来实现。
getView是用来刷新ListView的函数,每次在ListView里新增(新显示)一条记录时,getView就会被调用一次(在这次调用里,getView里就会对这条记录里的按钮设置监听器)。
下面是示例:
这是重写的类:MySimpleAdapter,里面的context变量是为了调用Toast类的makeText函数。
package com.plan; import java.util.List; import java.util.Map; import android.content.Context; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.SimpleAdapter; import android.widget.Toast; import com.example.plan.R; public class MySimpleAdapter extends SimpleAdapter{ Context context; public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); this.context = context; // TODO Auto-generated constructor stub } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v = super.getView(position, convertView, parent); Button btn=(Button) v.findViewById(R.id.button1); final int p = position; Log.d("Position", Integer.toString(position)); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(context, "删除"+Integer.toString(p),2000).show(); } }); return v; } }
使用上述类的代码:
plan_list = (ListView)findViewById(R.id.listView_today_plan);//找到控件 ListAdapter adapter = null;//绑定适配器 String[] time={"11:09","11:09","11:09"}; ,"HelloWorld"}; boolean[] check = {true,false,false}; List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>(); for(int i = 0; i < time.length;i++){ Map<String,Object> map = new HashMap<String,Object>(); map.put("time", time[i]); map.put("item", item[i]); map.put("check", check[i]); listItems.add(map); } adapter = new MySimpleAdapter(this,listItems, R.layout.plan_item, new String[]{"time","item","check"}, new int[]{R.id.textView_time,R.id.textView_item,R.id.checkBox_complish}); plan_list.setAdapter(adapter);
?重写SimpleAdapter的getView以实现按钮点击响应
标签:android
原文地址:http://blog.csdn.net/veloi/article/details/45868663