Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect scroll view reaching its top - Android

Tags:

android

scroll

I have used scrollview in my Android app using activity_main.xml. The scroll is working perfectly. But the thing is i need to add a Scroll to top button so that if the user starts scrolling the button should be visible like the link below..

http://webdesignerwall.com/demo/scroll-to-top/scrolltotop.html?

I need to do this in Android..

like image 414
Jessie Ka Avatar asked May 18 '15 05:05

Jessie Ka


People also ask

What is scrollEventThrottle?

scrollEventThrottle: It is used to control the firing of scroll events while scrolling.

Can scroll vertically Android?

In Android, a ScrollView is a view group that is used to make vertically scrollable views. A scroll view contains a single direct child only. In order to place multiple views in the scroll view, one needs to make a view group(like LinearLayout) as a direct child and then we can define many views inside it.

What is horizontal scroll view in Android?

HorizontalScrollView is used to scroll the child elements or views in a horizontal direction. HorizontalScrollView only supports horizontal scrolling. For vertical scroll, android uses ScrollView. Let's implement simple example of HorizontalScrollView.


1 Answers

Use the below code to detect the top of the scroll.

final ViewTreeObserver.OnScrollChangedListener onScrollChangedListener = new
            ViewTreeObserver.OnScrollChangedListener() {

                @Override
                public void onScrollChanged() {
                    if (scrollview.getScrollY() == 0) {
                        swipeRefreshLayout.setEnabled(true);
                    } else
                        swipeRefreshLayout.setEnabled(false);
                }
            };
    scrollview.setOnTouchListener(new View.OnTouchListener() {
        private ViewTreeObserver observer;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (observer == null) {
                observer = scrollview.getViewTreeObserver();
                observer.addOnScrollChangedListener(onScrollChangedListener);
            } else if (!observer.isAlive()) {
                observer.removeOnScrollChangedListener(onScrollChangedListener);
                observer = scrollview.getViewTreeObserver();
                observer.addOnScrollChangedListener(onScrollChangedListener);
            }
            return false;
        }
    });
like image 160
Tarun Gupta Avatar answered Oct 08 '22 12:10

Tarun Gupta