Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List view snap to item

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 would like to when the user stops scrolling that the first item of the visible list would snap to the top of screen, for example, if the scroll ends and small part of the first picture displayed, we scroll the list down so the picture is always fully displayed, if mostly of the picture is displayed, we scroll the list up so the next picture is fully visible.

Is there a way to achieve this in android with the listview?

like image 279
Marcio Covre Avatar asked Dec 13 '10 18:12

Marcio Covre


People also ask

How do I scroll ListView horizontally in flutter?

To scroll a Flutter ListView widget horizontally, set scrollDirection property of the ListView widget to Axis. horizontal. This arranges the items side by side horzontally. Following is the basic syntax to arrange the items horizontally in a ListView and scroll them horizontally.


1 Answers

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.

like image 63
Marcio Covre Avatar answered Oct 13 '22 10:10

Marcio Covre