Android notifyDataSetChanged无法正常工作
作者:互联网
我有一个适配器,该适配器使用来自TreeMap的数据填充2个TextViews的ListView.
当用户在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);
但是,无论我尝试做什么,列表都不会更新.我需要关闭并重新打开活动以获取新列表.
解决方法:
在您的适配器中创建一个方法,例如:
public void updateList(){
notifyDataSetChanged()
}
并在要刷新列表时调用此方法
标签:notifydatasetchanged,android,listview,android-arrayadapter 来源: https://codeday.me/bug/20191014/1911822.html