微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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() 
 }

并在要刷新列表调用方法

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐