记录一下,怕忘记了。
简单讲就是 向adapter中的list数据listData增加一项数据。然后调用adapter的 notifyDataSetChanged();方法就行了。
实现原理就是 当调用notifyDataSetChanged();后, adapter会把listdata重新遍历一遍,并且依次调用getView方法。
for (int i = 0; i < listData.size(); i++) {
getView( i, convertView, parent)
}
所以,你只需要在getView方法里做文章就好了。
一个简单示例:
public class MyListAdapter extends BaseAdapter{
List<Map<String, Object>> listData;
private LayoutInflater inflater;
public MyListAdapter(Context context,List<Map<String, Object>> listData){
this.listData = listData;
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return this.listData.size();
}
public Object getItem(int index) {
// TODO Auto-generated method stub
return this.listData.get(index);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){ // 如果当前这个位置的view已经加载过了就直接跳过
Map<String, Object> data = listData.get(position);
final String ipstr = (String) data.get("ip");
String gameNamestr = (String) data.get("gamename");
convertView = inflater.inflate(R.layout.netlist, null);
TextView gname = (TextView) convertView.findViewById(R.id.gamename);
gname.setText(gameNamestr);
TextView ip = (TextView) convertView.findViewById(R.id.ip);
ip.setText(ipstr);
Button btn = (Button) convertView.findViewById(R.id.conn);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
GamePlayer.ip = ipstr;
GamePlayer.ttClient.initClient(ipstr);
}
});
}
return convertView;
}
//调用此方法就可以实现增加一项数据
public void addItem(Map<String, Object> item){
this.listData.add(item);
notifyDataSetChanged();
}
}