List view snap to item

后端 未结 6 590
不思量自难忘°
不思量自难忘° 2020-12-02 17:45

I\'m creating a list of pictures using a ListView and the photos are of a size that would fit 2 to 3 photos on the screen.

The problem that I\'m having is that I wou

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 18:09

    I've found a way to do this just listening to scroll and change the position when the scroll ended by implementing ListView.OnScrollListener

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
        case OnScrollListener.SCROLL_STATE_IDLE:
            if (scrolling){
                // get first visible item
                View itemView = view.getChildAt(0);
                int top = Math.abs(itemView.getTop()); // top is a negative value
                int bottom = Math.abs(itemView.getBottom());
                if (top >= bottom){
                    ((ListView)view).setSelectionFromTop(view.getFirstVisiblePosition()+1, 0);
                } else {
                    ((ListView)view).setSelectionFromTop(view.getFirstVisiblePosition(), 0);
                }
            }
            scrolling = false;
            break;
        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
        case OnScrollListener.SCROLL_STATE_FLING:
            Log.i("TEST", "SCROLLING");
            scrolling = true;
            break;
        }
    }
    

    The change is not so smooth but it works.

提交回复
热议问题