0

I am trying to get a ListView to realign after every scroll/fling. By realign I mean realign in such a way, that the top item of the ListView is aligned with the top of the ListView, if it is cut off it should scroll down smoothly until it is realigned and fully visible.

I implemented a scroll-listener:

firstRowListView.setOnScrollListener(new OnScrollListener() {
        private boolean correcting = false;

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(AbsListView arg0, int scrollState) {
                if (!correcting && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                    correcting = true;
                    firstRowListView.smoothScrollToPosition(firstRowListView.getFirstVisiblePosition());
                    correcting = false;
                }
            }
        }
    });

(For easier visibility I only left the important bits in). If I scroll smoothly (no fling) it works fine, but if I fling the list it doesn't realign itself. Although LogCat tells me that the onScrollStateChange-method is executed in the same way as when I perform a "normal" scroll.

Why is this and how do I get the ListView to realign even after a Fling?

4

2 回答 2

1

以下应该可以工作,但在 Galaxy tab 7 (4.0.4) 上我可以看到递归正在发生。因此,我强烈建议您实施一些机制以避免这种情况,否则此解决方案将在某些设备上中断:

mylv.setOnScrollListener(new OnScrollListener() { 
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(final AbsListView lv,
                int scrollState) { 
            if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { 
                lv.post(new Runnable() {

                    @Override
                    public void run() {
                        lv.smoothScrollToPosition(lv
                                .getFirstVisiblePosition());  
                    }
                }); 
            }
        }
    });
于 2012-12-26T16:45:14.923 回答
0

在较旧的设备ListView上不报告SCROLL_STATE_IDLESCROLL_STATE_TOUCH_SCROLL。请使用此处提到的解决方法。http://code.google.com/p/android/issues/detail?id=5086#c7

您也可以correcting安全地删除变量,因为它在此代码中没有用。

于 2012-12-26T14:46:37.520 回答