自定义listview的显示(重写Adapter)
public class ListViewTest extends ListActivity {
/** Called when the activity is first created. */
private List<Map<String,Object>> mData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mData = getData();
MyAdapter adapter = new MyAdapter(this);
setListAdapter(adapter);
}
private List<Map<String,Object>> getData()
{
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "chen");
map.put("phone", "1376588****");
map.put("img",R.drawable.icon);
list.add(map);
return list;
}
public class ViewHolder
{
public ImageView img;
public TextView name;
public TextView phone;
public CheckBox check;
}
//重写Adapter,自己给Adapter加View,可以自定义listview每行显示的内容,如加Chekcbox,button等。Listview的多选框不好用,用这个能解决问题。
public class MyAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
public MyAdapter (Context context)
{
this.mInflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(view == null)
{
holder = new ViewHolder();
view = mInflater.inflate(R.layout.listview, null);
holder.img=(ImageView)view.findViewById(R.id.img);
holder.name=(TextView)view.findViewById(R.id.name);
holder.phone=(TextView)view.findViewById(R.id.phone);
holder.check=(CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else
{
holder=(ViewHolder)view.getTag();
}
holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
holder.name.setText((String)mData.get(position).get("name"));
holder.phone.setText((String)mData.get(position).get("phone"));
holder.check.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton ch, boolean arg1) {
// TODO Auto-generated method stub
Log.d("checkBox",""+ch.isChecked());
Log.d("check",""+mData.get(0).get("phone"));
}
});
return view;
}
}
}