Search code examples
androidandroid-viewandroid-gestureandroid-touch-event

How to set movement listener for a view


I have to listen for the position change of a particular view. The view can be anywhere , like , it can be an item of the listview or recycler view , or it can be a child of a scrollview or nested scrollview etc. But whenever the position in the screen of the view has been changed (Whenever the x,y coordinates being updated ), I need to be notified. I tried

view.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View view, int i, int i1, int i2, int i3) {
            Log.d(TAG, "Position changed");
        }
    });

and

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Log.d(TAG, "Layout changed");
        }
    });

But doesn't seem to work

I tried GestureDetectorCompat also , But during fling , the x,y positions are not accurate.

Is there any solution for my issue? Hope my issue is clear. Thanks in advance!!


Solution

  • I think you can make use of ViewTreeObserver.OnScrollChangedListener callback. This is the callback invoked when something in the view tree has been scrolled. So try adding this listener for your view which is moving.

    view.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                // Do what you want to do when the view has been scrolled
            }
        });