Search code examples
androidlistviewonscrolllistener

When the listitems are scrolled fast, setOnScrollListener is not working


I tried to implement the sticky header listview described in the tutorial from

http://javatechig.com/android/listview-header-parallax-with-sticky-view-in-android

The problem is when I scroll the list very fast, the header doesnot move to the top of screen as desired.

I tried logging the value of topY and heroTopY in the following method.

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

            /* Check if the first item is already reached to top.*/
            if (view.getFirstVisiblePosition() == 0) {
                View firstChild = listView.getChildAt(0);
                topY = 0;
                if (firstChild != null) {
                    topY = firstChild.getTop();
                    Log.d("topY", "" + topY);
                }

                heroTopY = stickyViewSpacer.getTop();
                Log.e("heroTopY", "" + heroTopY);
                Log.d("topY,heroTopY", topY + "," + heroTopY);
                stickyView.setY(Math.max(0, heroTopY + topY));

                // Set the image to scroll half of the amount that of ListView
                heroImageView.setY(topY * 0.5f);
            }
        }

The log output is:

09-01 17:35:23.692  19530-19530/com.javatechig.parallaxlistview D/topY﹕ 0
09-01 17:35:23.692  19530-19530/com.javatechig.parallaxlistview E/heroTopY﹕ 500
09-01 17:35:23.692  19530-19530/com.javatechig.parallaxlistview D/topY,heroTopY﹕ 0,500
09-01 17:35:23.856  19530-19530/com.javatechig.parallaxlistview D/topY﹕ -29
09-01 17:35:23.856  19530-19530/com.javatechig.parallaxlistview E/heroTopY﹕ 500
09-01 17:35:23.856  19530-19530/com.javatechig.parallaxlistview D/topY,heroTopY﹕ -29,500
09-01 17:35:23.873  19530-19530/com.javatechig.parallaxlistview D/topY﹕ -72
09-01 17:35:23.873  19530-19530/com.javatechig.parallaxlistview E/heroTopY﹕ 500
09-01 17:35:23.873  19530-19530/com.javatechig.parallaxlistview D/topY,heroTopY﹕ -72,500
09-01 17:35:23.892  19530-19530/com.javatechig.parallaxlistview D/topY﹕ -84
09-01 17:35:23.892  19530-19530/com.javatechig.parallaxlistview E/heroTopY﹕ 500
09-01 17:35:23.892  19530-19530/com.javatechig.parallaxlistview D/topY,heroTopY﹕ -84,500

As seen from the log output the topY value get stucked at 84 and so the header. enter image description here How to solve this??Any solution would be helpful!!!


Solution

  • add these lines

    if (view.getFirstVisiblePosition() == 0) {
    .....
    .....
    }
    else
    {
      stickyView.setY(0);
    }
    

    It is because when 1st item gets out of view you dont get inside if statement means topY is not updated so you have to set your stickyView.setY() to 0 on else statement.