【发布时间】:2015-02-27 09:16:53
【问题描述】:
我有一个适配器,它使用来自 TreeMap 的数据填充 ListView 和 2 个 TextView。 当用户从 ListView 添加或删除 Data 时,应刷新 View。
这是我的适配器:
public class MyAdapter extends BaseAdapter {
private final ArrayList mData;
public MyAdapter(Map<String, String> map) {
mData = new ArrayList();
mData.addAll(map.entrySet());
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Map.Entry<String, String> getItem(int position) {
return (Map.Entry) mData.get(position);
}
@Override
public long getItemId(int position) {
// TODO implement you own logic with ID
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View result;
if (convertView == null) {
result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
} else {
result = convertView;
}
Map.Entry<String, String> item = getItem(position);
// TODO replace findViewById by ViewHolder
((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());
return result;
}}
因为我想从对话框更新视图,并且在我阅读的另一个问题上,需要从 UIThread 调用 notifyDataSetChanged(),所以我将 notifyDataSetChanged() 放入 Runnable。就是这样:
Runnable run = new Runnable(){
public void run(){
Log.v("in the Runnable: ", String.valueOf(colorHashMap));
adapter.notifyDataSetChanged();
}
};
这就是在对话框中调用 Runnable 的方式:
DefaultColorActivity.this.runOnUiThread(run);
但无论我尝试或做什么,列表都不会更新。我需要关闭并重新打开活动以获取新列表。
【问题讨论】:
-
您在哪里添加和删除列表视图代码中的数据?
标签: android listview android-arrayadapter notifydatasetchanged