android:smoothScrollToPosition() 不能正常工作

问题描述:

在将元素添加到与列表视图关联的数组适配器后,我尝试平滑滚动到列表的最后一个元素.问题是它只是滚动到一个随机位置

I'm trying to smoothly scroll to last element of a list after adding an element to the arrayadapter associated with the listview. The problem is that it just scrolls to a random position

arrayadapter.add(item);
//DOES NOT WORK CORRECTLY:
listview.smoothScrollToPosition(arrayadapter.getCount()-1);

//WORKS JUST FINE:
listview.setSelection(arrayadapter.getCount()-1);

当 UI 线程可以处理滚动时,您可能希望告诉 ListView 发布滚动(这就是为什么它不能正确滚动的原因).SmoothScroll 需要做很多工作,而不是仅仅去一个忽略速度/时间/等的位置.(动画"需要).

You probably want to tell the ListView to post the scroll when the UI thread can handle it (which is why yours it not scrolling properly). SmoothScroll needs to do a lot of work, as opposed to just go to a position ignoring velocity/time/etc. (required for an "animation").

因此,您应该执行以下操作:

Therefore you should do something like:

    getListView().post(new Runnable() {
        @Override
        public void run() {
            getListView().smoothScrollToPosition(pos);
        }
    });