UI blocks when refreshing a listview (how to solve?)

非 Y 不嫁゛ 提交于 2019-12-11 08:34:47

问题


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

What I am experiencing:

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)

Question:

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

My Code:

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

EDIT:

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

回答1:


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...



来源:https://stackoverflow.com/questions/25575480/ui-blocks-when-refreshing-a-listview-how-to-solve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!