This source file includes following definitions.
- getPositionX
- getPositionY
- addListener
- removeListener
- notifyListeners
- updatePosition
package org.chromium.content.browser;
import android.view.View;
import android.view.ViewTreeObserver;
import java.util.ArrayList;
public class ViewPositionObserver implements PositionObserver {
private View mView;
private final int[] mPosition = new int[2];
private final ArrayList<Listener> mListeners;
private ViewTreeObserver.OnPreDrawListener mPreDrawListener;
public ViewPositionObserver(View view) {
mView = view;
mListeners = new ArrayList<Listener>();
updatePosition();
mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
updatePosition();
return true;
}
};
}
@Override
public int getPositionX() {
updatePosition();
return mPosition[0];
}
@Override
public int getPositionY() {
updatePosition();
return mPosition[1];
}
@Override
public void addListener(Listener listener) {
if (mListeners.contains(listener)) return;
if (mListeners.isEmpty()) {
mView.getViewTreeObserver().addOnPreDrawListener(mPreDrawListener);
updatePosition();
}
mListeners.add(listener);
}
@Override
public void removeListener(Listener listener) {
if (!mListeners.contains(listener)) return;
mListeners.remove(listener);
if (mListeners.isEmpty()) {
mView.getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener);
}
}
private void notifyListeners() {
for (int i = 0; i < mListeners.size(); i++) {
mListeners.get(i).onPositionChanged(mPosition[0], mPosition[1]);
}
}
private void updatePosition() {
int previousPositionX = mPosition[0];
int previousPositionY = mPosition[1];
mView.getLocationInWindow(mPosition);
if (mPosition[0] != previousPositionX || mPosition[1] != previousPositionY) {
notifyListeners();
}
}
}