【问题标题】:no change/black screen by notifyDataSetChanged();notifyDataSetChanged() 没有变化/黑屏;
【发布时间】:2012-06-29 00:46:08
【问题描述】:

我想做这样的事情。

按下刷新按钮时,它会刷新列表。活动代码是这样的:

        adapter = new TweetAdapter(Welcome.this, tweets, users);
        tweetsList.setAdapter(adapter);


    private void refreshAdapter() {
        adapter.clear();
        adapter.refresh(tweets, users);
    }

refreshAdapter() 在我需要更改列表项时调用。这里tweets & usersArrayList & HashMap 项目

而适配器部分是这样的:

public void clear() {
    this.tweets.clear();
    this.users.clear();
}

public void refresh(ArrayList<Tweet> tweets, HashMap<String, User> users) {
    this.tweets.addAll(tweets);
    this.users.putAll(users);
    Collections.sort(this.tweets, new TweetTimeComparator());
    notifyDataSetChanged();
}

但不幸的是,notifyDataSetChanged(); 无法正常工作。通过单击刷新,列表要么变黑(最长时间),要么没有响应(一段时间)。

如果您发现错误,请告诉我或建议我该怎么做。

【问题讨论】:

    标签: android listview adapter baseadapter


    【解决方案1】:

    我认为你正在清除数据

    this.tweets.clear();
    this.users.clear();
    

    .. 我认为由于推文和用户都具有相同的引用(从活动传递到适配器),所以推文和两个用户(在适配器和活动上都指向相同的 ArrayLists)所以两者都很清楚,所以这些行都没有意义是空的

    this.tweets.addAll(tweets);
    this.users.putAll(users);
    

    试试

    public TweetAdapter(Context context, ArrayList<Tweet> tweets, HashMap<String, User> users) { 
    
    mInflater = LayoutInflater.from(context); 
    this.tweets = new ArrayList<Tweet>(); 
    this.users = new HashMap<String, User>();
    
    this.tweets.addAll(tweets);
    this.users.putAll(users);
    
    Collections.sort(this.tweets, new TweetTimeComparator()); 
    } 
    

    ..

    public void refresh(ArrayList<Tweet> tweets, HashMap<String, User> users) {
    
      this.tweets.clear();
        this.users.clear();
    
        this.tweets.addAll(tweets);
        this.users.putAll(users);
        Collections.sort(this.tweets, new TweetTimeComparator());
        notifyDataSetChanged();
    }
    

    但是注意:现在引用两个推文(在适配器和活动上)和两个用户(在适配器和活动上)是不同的。

    在其他使用 this.tweets.addAll(tweets); 的地方不应该有像 adapter.tweets = activity.tweets 这样的直接赋值;

    【讨论】:

    • 那该怎么办?? this.users.clear();不是很重要,因为我可以使用旧的用户集,但是 this.tweets.clear();对于刷新新推文很重要。
    • public TweetAdapter(Context context, ArrayList&lt;Tweet&gt; tweets, HashMap&lt;String, User&gt; users) { mInflater = LayoutInflater.from(context); this.tweets = tweets; this.users = users; Collections.sort(this.tweets, new TweetTimeComparator()); }
    • 是的……你是对的。刚刚调试并发现两者都是空的:(
    • 谢谢我的朋友,它的工作。刚刚推特并用新推文刷新了:)实际上我犯了一个基本的大错误,没有做this.tweets = new ArrayList&lt;Tweet&gt;();等等......再次感谢。
    • 嘿嘿.. 终于完成了。你无法想象我在哪里发现了这个错误,实际上它不可能远程进行。下载新推文的活动的推文价值翻倍/三倍。我只是在活动中添加新的新推文集之前添加了 tweets.clear(),然后通过 clear() 然后 refresh() 传递它。否则一切正常。适配器中的 clear() 正在工作,我已经感谢你 this.tweets=new ArrayList();再次感谢您尝试解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2018-12-11
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多