Android ListView - stop scrolling at 'whole' row position

前端 未结 7 1410
生来不讨喜
生来不讨喜 2020-12-29 11:46

Sorry for the confusing title, I cannot express the problem very concisely...

I have an Android app with a ListView that uses a circular / \"infinite\" adapter, whi

相关标签:
7条回答
  • 2020-12-29 12:20

    You probably solved this problem but I think that this solution should work

    if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
        View firstChild = lv.getChildAt(0);
        int pos = lv.getFirstVisiblePosition();
    
        //if first visible item is higher than the half of its height
        if (-firstChild.getTop() > firstChild.getHeight()/2) {
            pos++;
        }
    
        lv.setSelection(pos);
    }
    

    getTop() for first item view always return nonpositive value so I don't use Math.abs(firstChild.getTop()) but just -firstChild.getTop(). Even if this value will be >0 then this condition is still working.

    If you want to make this smoother then you can try to use lv.smoothScrollToPosition(pos) and enclose all above piece of code in

    if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
        post(new Runnable() {
            @Override
            public void run() {
                //put above code here
                //and change lv.setSelection(pos) to lv.smoothScrollToPosition(pos)
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题