Sam YC
Sam YC

Reputation: 11617

Listen on a View if the View change its XY position

How do I listen on a View to obtain its XY coordination if it is moving or its XY position change? The View is not necessary to be dragged (or by user touch event), it may change if the orientation change or pushed (upward) by the showing keyboard or etc. I want to know its updated XY coordination when it changes, how can I do that?

Upvotes: 9

Views: 7159

Answers (2)

Renetik
Renetik

Reputation: 6373

Probably addOnLayoutChangeListener should work. It is called when in layout function of the view it find out the frame bounds changes. If the frame bounds doesn't change so basically if the parent bounds change instead and that changes view location, we probably dont get this event here and then some addOnGlobalLayoutListener with som additional code that will compare real location on screen will be necessary but I would not go that way, because it attracts additional issues.

Upvotes: 1

Chandrashekhar
Chandrashekhar

Reputation: 498

You may do something like this

final View activityRootView = findViewById(R.id.mainLayout);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onGlobalLayout() {
                        findViewById(R.id.textView).getX();
                        findViewById(R.id.textView).getY();

                    }
                });

Hope this helps.

Upvotes: 12

Related Questions