Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView scroll - one by one

I have a ListView that must display 4 items at a time. And I must scroll one item, one by one.

After user scrolls the ListView, I must readjust the scroll to fit 4 items. I mean, I can´t show an item by half.

Another question, is there any way to get the current ListView scrollY offset? Because the listView.getScrollY() method is from View, but not the Scroller object inside the ListView.

like image 981
rlecheta Avatar asked Jun 22 '26 18:06

rlecheta


1 Answers

I've found an excellent solution. It works perfect for me. May be my answer will help someone.

class ScrollListener implements AbsListView.OnScrollListener{
        boolean aligned;

        @Override
        public void onScrollStateChanged(AbsListView absListView, int state) {
            if (state == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                aligned = false;
            }
            if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                if (!aligned) {
                    if (Math.abs(absListView.getChildAt(0).getY()) < Math.abs(absListView.getChildAt(1).getY())) {
                        listView.smoothScrollToPosition(absListView.getFirstVisiblePosition());
                    } else {
                        listView.smoothScrollToPosition(absListView.getLastVisiblePosition());
                    }
                }
                aligned = true;
            }
        }

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

I must say that in my situation I had two visible items so if you have 4 you should play with indexes ("getChildAt(0)" and "getChildAt(1)"). Good luck!

like image 62
Shamm Avatar answered Jun 25 '26 08:06

Shamm