Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect when my View has moved?

Tags:

android

I have a View in my Activity. I want to detect when it has moved around the screen due to any actions (user scrolls, relative views resize shifting contents, etc.). This is meant to be in a library, so I can query the hierarchy, but I don't control it, nor can I modify it other than adding event listeners.

Is there any way to get this as an event, rather than polling?

like image 746
Hounshell Avatar asked Mar 08 '12 07:03

Hounshell


1 Answers

There is an event for this: View.getViewTreeObserver().addOnScrollChangedListener()

final ViewTreeObserver.OnScrollChangedListener mScrollChangedListener = ...;

@Override
protected void onAttachedToWindow() {
  super.onAttachedToWindow();
  getViewTreeObserver().addOnScrollChangedListener(mScrollChangedListener);
}

@Override
protected void onDetachedFromWindow() {
  super.onDetachedFromWindow();
  getViewTreeObserver().removeOnScrollChangedListener(mScrollChangedListener);
}

Source: Android Source Code (4.0), android.view.SurfaceView.java:205

like image 182
Hounshell Avatar answered Oct 02 '22 10:10

Hounshell