public class Custom_BaseAdapterActivity extends ListActivity {
List<Map<String,Object>> list;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
list = getListData();
setContentView(R.layout.listdemo2);
MyAdapter myAdapter = new MyAdapter(this);
setListAdapter(myAdapter);
}
public List<Map<String,Object>> getListData(){
list = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 = new HashMap<String,Object>();
Map<String,Object> map2 = new HashMap<String,Object>();
map1.put("headimg", R.drawable.lxq);
map1.put("nickname", "蜗牛/");
map1.put("textsign", "乘着风游荡在蓝天边 一片云掉落在我面前.");
map2.put("headimg", R.drawable.hyl);
map2.put("nickname", "轩凌涵舞");
map2.put("textsign", "以后我儿子得有两门必修课,打篮球和拉小提琴.");
list.add(map1);
list.add(map2);
return list;
}
public final class ViewHolder{
public ImageView headimg;
public TextView nickname;
public TextView textsign;
public Button listbtn;
}
public class MyAdapter extends BaseAdapter{
private LayoutInflater flater;
public MyAdapter(Context context) {
super();
this.flater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = flater.inflate(R.layout.user2, null);
holder.headimg = (ImageView) convertView.findViewById(R.id.headimg);
holder.nickname = (TextView) convertView.findViewById(R.id.nickname);
holder.textsign = (TextView) convertView.findViewById(R.id.textsign);
holder.listbtn = (Button) convertView.findViewById(R.id.listbtn);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.headimg.setBackgroundResource((Integer)list.get(position).get("headimg"));
holder.nickname.setText((String)list.get(position).get("nickname"));
holder.textsign.setText((String)list.get(position).get("textsign"));
holder.listbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
}
});
return convertView;
}
}
}
只有在convertView为null时才去实例化控件,创建convertView对象、holder对象,其中convertView对象是通过mInflater.inflate(R.layout.main, null)方法,从一个main.xml布局文件中加载并创建的。
而在convertView非null的时候不会实例化控件,否则每次都要实例化控件,当列表项目很多时,用户反复滑动屏幕会有“卡”的感觉,不再流畅了。