如果数据来源是Json的情况下:
//从json对象中获得user对象
public User(JSONObject object) {
try {
this.name = object.getString("name");
this.hometown = object.getString("hometown");
} catch (JSONException e) {
e.printStackTrace();
}
}
//将一组user对象存储在数组列表中,首先要获得Json数组
public static ArrayList<User> fromJson(JSONArray jsonObjects) {
ArrayList<User> users = new ArrayList<User>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
users.add(new User(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return users;
}
}
优化ListView
public class UserAdapter extends ArrayAdapter<User> {
//使用viewHolder缓存数据
private static class ViewHolder {
TextView name;
TextView home;
}
@Override
public View getView(int position , View convertView, ViewGroup parent) {
//获得相应位置的类
User user = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
//加载两个textView视图
viewHolder.name = (TextView) convertView.findViewById(R.id.tvName);
viewHolder.home = (TextView) convertView.findViewById(R.id.tvHome);
//将viewHolder存贮在convertView中
convertView.setTag(viewHolder);
} else {
//将convertView中存储的数据还原成viewHolder
viewHolder = (viewHolder) convertView.getTag();
}
viewHolder.name.setText(user.name);
viewHolder.home.setText(user.hometown);
return convertView;
}
}