Android ListView - stop scrolling at 'whole' row position

前端 未结 7 1457
生来不讨喜
生来不讨喜 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

    Here's my final code inspired by Shade's answer.

    I forgot to add "if(Math.abs(r.height())!=height)" at first. Then it just scrolls twice after it scroll to correct position because it's always greater than height/2 of childView. Hope it helps.

    listView.setOnScrollListener(new AbsListView.OnScrollListener(){
    
                @Override
                public void onScrollStateChanged(AbsListView view,int scrollState) {
                    if (scrollState == SCROLL_STATE_IDLE){
                        View child = listView.getChildAt (0);    // first visible child
                        Rect r = new Rect (0, 0, child.getWidth(), child.getHeight());     // set this initially, as required by the docs
                        double height = child.getHeight () * 1.0;
                        listView.getChildVisibleRect (child, r, null);
                        if(Math.abs(r.height())!=height){//only smooth scroll when not scroll to correct position
                            if (Math.abs (r.height ()) < height / 2.0) {
                                listView.smoothScrollToPosition(listView.getLastVisiblePosition());
                            }
                            else if(Math.abs (r.height ()) > height / 2.0){
                                listView.smoothScrollToPosition(listView.getFirstVisiblePosition());
                            }
                            else{
                                listView.smoothScrollToPosition(listView.getFirstVisiblePosition());
                            }
    
                        }
                    }
                }
    
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
    
                }});
    

提交回复
热议问题