Andrew
Andrew

Reputation: 21076

Getting a View's position

I'd like to get the distance of a View from the top of a device's screen.

I'm using animations to do some things with my Activity and I need an Animation to begin at a certain point. This is a TranslateAnimation and it is given a distance to travel in terms of percentages.

Ex:

Animation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.1f, Animation.RELATIVE_TO_PARENT, 0.0f
            );

The above code is used to animate a view starting at 10% below the top of the screen and moving it upwards until it aligned with the top of the screen.

For my purposes, the value 0.1f can't be hard coded because the exact value needed may change with different devices. I need a way to determine what dynamic value I should use in place of 0.1f. This value should be the distance from the top of the screen a another specific View is.

So, basically, what I'm wanting is a way to take an existing View on the screen and determine how far it is from the top of the screen.

Upvotes: 0

Views: 121

Answers (2)

devunwired
devunwired

Reputation: 63293

The View class has two convenience methods, getLocationOnScreen() and getLocationInWindow() that allow you to get directly the location of a view with respect to the entire display, rather than just its parent view. The methods take a pre-initializes int[] where the x/y location will be filled in.

The methods getLeft() and getTop() may be useful as well, but keep in mind these will return the coordinate of the given with with respect to its parent, which may or may not be what you need in this case.

Upvotes: 2

SteveR
SteveR

Reputation: 2506

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

From Android developer site

Upvotes: 0

Related Questions