刷新列表视图时,UI会阻塞(如何解决?) [英] UI blocks when refreshing a listview (how to solve?)

查看:90
本文介绍了刷新列表视图时,UI会阻塞(如何解决?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮.点击后,我正在刷新列表.

I have a button. On click, I am refreshing a list.

我正在经历的事情:

state_pressed 颜色保持很长一段时间(这意味着UI线程被阻止)
(注意:按钮的背景已定义,例如在state_pressed ="true"上颜色会发生变化)

The state_pressed color stays for a big while (meaning the UI thread blocked)
(Note: the button background is defined such as on state_pressed="true" the color changes)

问题:

如何在不阻止UI的情况下单击按钮刷新列表?

How can I click the button to refresh the list, without blocking the UI?

我的代码:

mButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        refreshListView(data);
    }
});

public void refreshListView(ArrayList data) {
    // I am setting setNotifyOnChange() to false
    // to prevent notifyDataSetChanged() to be triggered twice, by clear() and by addAll()
    mArrayAdapter.setNotifyOnChange(false)
    mArrayAdapter.clear();
    mArrayAdapter.addAll(data);
    // I am triggering notifyDataSetChanged() explicitely
    mArrayAdapter.notifyDataSetChanged();
    mListView.post(new Runnable() {
        @Override
        public void run() {
            // this is to reset to the top of the list, after the list has been populated
            mListView.setSelectionAfterHeaderView();
        }
    });
}

编辑:

我认为我是通过从View.post()调用刷新代码来解决此问题的,但我想知道是否始终需要这样做:

I think I solved it by calling the refresh code from a View.post(), but I wonder if this should always be needed:

mButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        mListView.post(new Runnable() {
            @Override
            public void run() {
                refreshListView(data);
            }
        });
    }
});

推荐答案

您的refreshList应该在ui线程上运行...并且新的Runnable应该与线程一起使用...如果不创建新线程,则您将会使用Runnable作为匿名类...按照android的标准,这不是一个好习惯...但是,如果这解决了您的问题,从技术上讲,您的代码中没有错...

Your refreshList should be running on ui thread... and new Runnable should be used in conjunction with thread... If you are not creating new Thread, you will be using Runnable as kind of anonymous class... As par android this is not good practice... But, well if this solves your problem, technically there is nothing wrong in your code...

这篇关于刷新列表视图时,UI会阻塞(如何解决?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆