通过以下代码更新 ListView 的内容:
private ListView listViewBuddy;
private BuddyAdapter mBuddyAdapter;
private ArrayList<BuddyModel> buddyList = new ArrayList<BuddyModel>();
onCreate():
listViewBuddy = (ListView)findViewById(R.id.listViewBuddy);
mBuddyAdapter = new BuddyAdapter();
listViewBuddy.setAdapter(mBuddyAdapter);
onDataGet(在网络服务调用或从本地数据库或其他):
mBuddyAdapter.setData(buddyList);
mBuddyAdapter.notifyDataSetChanged();
基础适配器:
private class BuddyAdapter extends BaseAdapter {
private ArrayList<BuddyModel> mArrayList = new ArrayList<BuddyModel>();
private LayoutInflater mLayoutInflater= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private ViewHolder holder;
public void setData(ArrayList<BuddyModel> list){
mArrayList = list;
}
@Override
public int getCount() {
return mArrayList.size();
}
@Override
public BuddyModel getItem(int position) {
return mArrayList.get(position);
}
@Override
public long getItemId(int pos) {
return pos;
}
private class ViewHolder {
private TextView txtBuddyName, txtBuddyBadge;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.row_buddy, null);
// bind views
holder.txtBuddyName = (TextView) convertView.findViewById(R.id.txtBuddyName);
holder.txtBuddyBadge = (TextView) convertView.findViewById(R.id.txtBuddyBadge);
// set tag
convertView.setTag(holder);
} else {
// get tag
holder = (ViewHolder) convertView.getTag();
}
holder.txtBuddyName.setText(mArrayList.get(position).getFriendId());
int badge = mArrayList.get(position).getCount();
if(badge!=0){
holder.txtBuddyBadge.setVisibility(View.VISIBLE);
holder.txtBuddyBadge.setText(""+badge);
}else{
holder.txtBuddyBadge.setVisibility(View.GONE);
}
return convertView;
}
}
每当您想更新 Listview时,只需调用以下两行代码:
mBuddyAdapter.setData(Your_Updated_ArrayList);
mBuddyAdapter.notifyDataSetChanged();
完毕