Android 如果使用HashMap,如何在BaseAdapter getView()中迭代
我有一个扩展自Android 如果使用HashMap,如何在BaseAdapter getView()中迭代,android,Android,我有一个扩展自BaseAdapter类,它用作我的列表视图的自定义适配器。如果我使用List作为数据集,我在getView()方法中没有任何问题,并且一切正常-我的列表中填充了List中的所有数据。但是,如果我使用HashMap,这是行不通的。据我所知,getView()遍历集合,这对List很好,因为它是可编辑的 private class MAdapter extends BaseAdapter { private LayoutInflater mInflater;
BaseAdapter
类,它用作我的列表视图的自定义适配器。如果我使用List
作为数据集,我在getView()
方法中没有任何问题,并且一切正常-我的列表中填充了List
中的所有数据。但是,如果我使用HashMap
,这是行不通的。据我所知,getView()
遍历集合,这对List
很好,因为它是可编辑的
private class MAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.list_item, null);
}
Task task = taskList.get(position); // works perfect if taskList is List and doesn't work if it is HashMap. What shell I do to use HashMap here?
if (task != null) {
TextView tvDescription = (TextView) v
.findViewById(R.id.task_text_view);
TextView tvTime = (TextView) v
.findViewById(R.id.time_text_view);
if (tvDescription != null) {
tvDescription.setText(task.getDescription());
}
if (tvTime != null) {
tvTime.setText(task.showTime());
}
}
return v;
}
你不能。BaseAdapter实现ListAdapter,之所以称为ListAdapter是有原因的。为什么要使用HashMap
更新:
从列表中删除
for(int j = list.size() - 1; j >= 0; j--){
Object o = list.get(j);
if(o.getId().equals(id)) {
list.remove(o); // find obj and remove
break;
}
}
adapter.notifyDataSetChanged(); // update ListView
或者同时保留列表和HashMap。我建议只使用列表
Object o = map.remove(id); // remove object by id
list.remove(o); // remvove object from list
adapter.notifyDataSetChanged(); // update ListView
因为我需要根据对象的Id从集合中删除对象,这是使用HashMap not List执行此操作的最佳方法。只需像我的示例中那样迭代列表并删除它。尝试链接它对我最有效