Can I get a View's x and y position relative to the root layout of my Activity in Android?
The Android API already provides a method to achieve that.
Try this:
Rect offsetViewBounds = new Rect();
//returns the visible bounds
childView.getDrawingRect(offsetViewBounds);
// calculates the relative coordinates to the parent
parentViewGroup.offsetDescendantRectToMyCoords(childView, offsetViewBounds);
int relativeTop = offsetViewBounds.top;
int relativeLeft = offsetViewBounds.left;
Here is the doc
This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.
private int getRelativeLeft(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}
private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
Let me know if that works.
It should recursively just add the top and left positions from each parent container.
You could also implement it with a Point if you wanted.
Please use view.getLocationOnScreen(int[] location); (see Javadocs). The answer is in the integer array (x = location[0] and y = location[1]).
View rootLayout = view.getRootView().findViewById(android.R.id.content);
int[] viewLocation = new int[2];
view.getLocationInWindow(viewLocation);
int[] rootLocation = new int[2];
rootLayout.getLocationInWindow(rootLocation);
int relativeLeft = viewLocation[0] - rootLocation[0];
int relativeTop = viewLocation[1] - rootLocation[1];
First I get the root layout then calculate the coordinates difference with the view.
You can also use the getLocationOnScreen() instead of getLocationInWindow().
No need to calculate it manually.
Just use getGlobalVisibleRect like so:
Rect myViewRect = new Rect();
myView.getGlobalVisibleRect(myViewRect);
float x = myViewRect.left;
float y = myViewRect.top;
Also note that for the centre coordinates, rather than something like:
...
float two = (float) 2
float cx = myViewRect.left + myView.getWidth() / two;
float cy = myViewRect.top + myView.getHeight() / two;
You can just do:
float cx = myViewRect.exactCenterX();
float cy = myViewRect.exactCenterY();
You can use `
view.getLocationOnScreen(int[] location)
;` to get location of your view correctly.
But there is a catch if you use it before layout has been inflated you will get wrong position.
Solution to this problem is adding ViewTreeObserver like this :-
Declare globally the array to store x y position of your view
int[] img_coordinates = new int[2];
and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates
// set a global layout listener which will be called when the layout pass is completed and the view is drawn
parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
//Remove the listener before proceeding
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// measure your views here
fab.getLocationOnScreen(img_coordinates);
}
}
);
and then use it like this
xposition = img_coordinates[0];
yposition = img_coordinates[1];
I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.
"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.
First a method that goes from descendant coordinates to ancestor:
public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
final float scrollX = descendant.getScrollX();
final float scrollY = descendant.getScrollY();
final float left = descendant.getLeft();
final float top = descendant.getTop();
final float px = descendant.getPivotX();
final float py = descendant.getPivotY();
final float tx = descendant.getTranslationX();
final float ty = descendant.getTranslationY();
final float sx = descendant.getScaleX();
final float sy = descendant.getScaleY();
point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
point[1] = top + py + (point[1] - py) * sy + ty - scrollY;
ViewParent parent = descendant.getParent();
if (descendant != ancestor && parent != ancestor && parent instanceof View) {
transformToAncestor(point, ancestor, (View) parent);
}
}
Next the inverse, from ancestor to descendant:
public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
ViewParent parent = descendant.getParent();
if (descendant != ancestor && parent != ancestor && parent instanceof View) {
transformToDescendant(point, ancestor, (View) parent);
}
final float scrollX = descendant.getScrollX();
final float scrollY = descendant.getScrollY();
final float left = descendant.getLeft();
final float top = descendant.getTop();
final float px = descendant.getPivotX();
final float py = descendant.getPivotY();
final float tx = descendant.getTranslationX();
final float ty = descendant.getTranslationY();
final float sx = descendant.getScaleX();
final float sy = descendant.getScaleY();
point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}
Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.
int pos[] = new int[2];
view.getLocationOnScreen(pos);
int centerX = pos[0] + view.getMeasuredWidth() / 2;
int centerY = pos[1] + view.getMeasuredHeight() / 2;
I just found the answer here
It says:
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.
so use:
view.getLeft(); // to get the location of X from left to right
view.getRight()+; // to get the location of Y from right to left
You can use the following the get the difference between parent and the view you interested in:
private int getRelativeTop(View view) {
final View parent = (View) view.getParent();
int[] parentLocation = new int[2];
int[] viewLocation = new int[2];
view.getLocationOnScreen(viewLocation);
parent.getLocationOnScreen(parentLocation);
return viewLocation[1] - parentLocation[1];
}
Dont forget to call it after the view is drawn:
timeIndicator.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
final int relativeTop = getRelativeTop(timeIndicator);
});
Related
I'm trying to scale view from start rectangle (e.g. defined by another view) to it's final position.
I tried to use the following code to setup animations which looks straight forward:
float scaleX = 0f;
float scaleY = 0f;
Rect startRect = new Rect(10, 10, 100, 100); // taken from real view position with getLocationOnScreen
final Collection<Animator> animators = new ArrayList<>();
if (animatedView.getMeasuredHeight() != 0) {
scaleX = (float)startRect.width() / animatedView.getMeasuredWidth();
}
if (animatedView.getMeasuredHeight() != 0) {
scaleY = (float)startRect.height() / animatedView.getMeasuredHeight();
}
animatedView.getLocationInWindow(location);
animatedView.setPivotX(startRect.left);
animatedView.setPivotY(startRect.top);
animatedView.setScaleX(scaleX);
animatedView.setScaleY(scaleY);
animators.add(ObjectAnimator.ofFloat(animatedView, View.SCALE_X, 1.0f).setDuration(1000));
animators.add(ObjectAnimator.ofFloat(animatedView, View.SCALE_Y, 1.0f).setDuration(1000));
The animatedView is child of RelativeLayout (layout parameters set to below some title view of layout) and measured width and height and location are valid values at the moment of animation setup.
Depending on startRect I observe different animations - sometimes animated view get displayed below or above startRect.
Seems RectEvaluator is one of possible solutions, but it's available only from API 18.
What is the proper way to animate view from start rectangle position to final (not modified one)?
As per comments on the question, it's possible to copy RectEvaluator code from Android source, and then apply the following logic:
RectViewAnimator mRectAnimator;
/**
* Creates animator which can be played. From some start position
* to final (real position).
* From final position to start position can be achieved using reverse interpolation.
*/
private Collection<Animator> createMoveAnimators(View targetView, Rect startRect) {
final Collection<Animator> animators = new ArrayList<>();
final int[] location = new int[2];
targetView.getLocationOnScreen(location);
final Rect finalRect = new Rect(location[0], location[1],
location[0] + targetView.getMeasuredWidth(),
location[1] + targetView.getMeasuredHeight());
// Must keep this reference during animations, since Animator keeps only WeakReference to it's targets.
mRectAnimator = appendRectEvaluatorAnimation(animators, targetView, 500, startRect, finalRect);
return animators;
}
private RectViewAnimator appendRectEvaluatorAnimation(final Collection<Animator> animators, final View view, final int duration,
final Rect startRect, final Rect finalRect) {
final float scaleX = (float) startRect.width() / finalRect.width();
final float scaleY = (float) startRect.height() / finalRect.height();
view.setTranslationY(startRect.top - (finalRect.top + (1 - scaleY) * finalRect.height() / 2));
view.setTranslationX(startRect.left - (finalRect.left + (1 - scaleX) * finalRect.width() / 2));
view.setScaleX(scaleX);
view.setScaleY(scaleY);
final RectViewAnimator rectViewAnimator = new RectViewAnimator(view, finalRect);
final Animator animator = ObjectAnimator.ofObject(rectViewAnimator, RectViewAnimator.RECT,
new RectEvaluator(), startRect, finalRect);
animators.add(animator);
return rectViewAnimator;
}
private static class RectViewAnimator {
static final String RECT = "rect";
private final View target;
private final Rect finalRect;
RectViewAnimator(final View target, final Rect finalRect) {
this.target = target;
this.finalRect = finalRect;
}
#Keep
public void setRect(final Rect r) {
final float scaleX = (float)r.width() / finalRect.width();
final float scaleY = (float)r.height() / finalRect.height();
target.setScaleX(scaleX);
target.setScaleY(scaleY);
target.setTranslationX(r.left - (finalRect.left + (1 - scaleX) * finalRect.width() / 2));
target.setTranslationY(r.top - (finalRect.top + (1 - scaleY) * finalRect.height() / 2));
}
}
My Android app has a game map with markers on it. When the user taps a marker, I'm displaying a PopupWindow aligned with the map marker (similar to Google Maps). The problem I'm having is if a marker is close to the top of the screen, the PopupWindow overlaps with the ActionBar (and under the status bar, if the marker is high enough).
I'm displaying the PopupWindow by calling showAtLocation(), which I'd hoped would constrain the view to inside the "Map" fragment (it does on the left and right sides), but that's not working.
I had already implemented an adjustment, to account for text inside the popup taking up more than one line, where I update the Y position of the popup after the View has been laid out. That worked with no problem, but when I tried to add another vertical adjustment for this situation, the PopupWindow's position does not change.
Here is the code for the PopupWindow implementation:
/**
* Displays a PopupWindow.
*/
public class MyPopupWindow extends PopupWindow
{
private Fragment m_fragment;
private int m_x;
private int m_y;
/**
* Displays a PopupWindow at a certain offset (x, y) from the center of fragment's view.
*/
public static MyPopupWindow createPopup (Context context, Fragment fragment, int x, int y)
{
// Create the PopupWindow's content view
LayoutInflater inflater = LayoutInflater.from (context);
View popupView = inflater.inflate (R.layout.view_map_popup, null);
MyPopupWindow popupWindow = new MyPopupWindow (popupView, x, y);
popupWindow.m_fragment = fragment;
popupWindow.showAtLocation (fragment.getView (), Gravity.CENTER, x, y);
return popupWindow;
}
private MyPopupWindow (View view, int x, int y)
{
super (view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
m_x = x;
m_y = y;
TextView title = (TextView) view.findViewById (R.id.lblMapPopupTitle);
title.setText ("Exercise Title");
TextView description = (TextView) view.findViewById (R.id.lblMapPopupDescription);
description.setText ("Exercise Description\nSecond Line\nThird Line\nFourth Line\nAnd one more...");
view.setVisibility (View.INVISIBLE);
view.addOnLayoutChangeListener (layoutChangeListener);
}
// If the tapped map location is too close to the edge, determine the
// delta-x and delta-y needed to align it with the PopupWindow
private int getHorizontalAdjustment (int popupWidth)
{
int horizontalAdjustment = 0;
int parentWidth = m_fragment.getView ().getWidth ();
if ((parentWidth / 2) + m_x + (popupWidth / 2) > parentWidth)
{
horizontalAdjustment = parentWidth - ((parentWidth / 2) + m_x + (popupWidth / 2));
}
else if ((parentWidth / 2) + m_x - (popupWidth / 2) < 0)
{
horizontalAdjustment = 0 - ((parentWidth / 2) + m_x - (popupWidth / 2));
}
return horizontalAdjustment;
}
private int getVerticalAdjustment (int popupHeight)
{
int verticalAdjustment = 0;
int parentHeight = m_fragment.getView ().getHeight ();
int y = m_y - (popupHeight / 2);
if ((parentHeight / 2) + y + (popupHeight / 2) > parentHeight)
{
verticalAdjustment = parentHeight - ((parentHeight / 2) + y + (popupHeight / 2));
}
else if ((parentHeight / 2) + y - (popupHeight / 2) < 20)
{
verticalAdjustment = 20 - ((parentHeight / 2) + y - (popupHeight / 2));
}
return verticalAdjustment;
}
private View.OnLayoutChangeListener layoutChangeListener = new View.OnLayoutChangeListener ()
{
#Override
public void onLayoutChange (View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)
{
int height = bottom - top;
int width = right - left;
// Adjust the y-position for the inflated height of the view
// (so the popup's bottom edge lines up with the tapped marker's top edge)
int y = m_y - (height / 2);
int x = m_x;
// Determine any adjustments that need to be made to line up the tapped marker with the popup
int horizontalAdjustment = getHorizontalAdjustment (width);
int verticalAdjustment = getVerticalAdjustment (height);
y -= verticalAdjustment;
// Update our position with the re-calculated position
update (x, y, -1, -1);
view.setVisibility (View.VISIBLE);
}
};
}
The issue can be seen in this screenshot: PopupWindow overlaps ActionBar
Basically, I need to either (1) get the PopupWindow to clip to the Fragment's view and not overlap the ActionBar, or (2) get the PopupWindow to update its position in the event that it does overlap the ActionBar.
Any help is greatly appreciated.
I want to get the coordinate positions of a button in my application.I used the following method.But its not working.Please help.
public Point currentPosition(View view)
{
int[] loc = new int[2];
view.getLocationOnScreen(loc);
int x = loc[0];
int y=loc[1];
Toast.makeText(getApplicationContext(),"coordinate is"+x+","+y,Toast.LENGTH_SHORT).show();
return new Point(loc[0], loc[1]);
}
Also i used this
btn_show.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
int x = (int)btn_show.getX();
int y= (int)btn_show.getY();
Toast.makeText(getApplicationContext(), "button x is......"+x,Toast.LENGTH_SHORT ).show();
Toast.makeText(getApplicationContext(), "button y is......"+y,Toast.LENGTH_SHORT ).show();
}
});
The method you use expect integer values as references of R.string.whatever. Cast the getTop() return value to String should work.
Toast.makeText(MainActivity.this, String.valueOf(button1.getTop()), Toast.LENGTH_LONG).show();
To get the x/y of the button (since API 11):
Toast.makeText(MainActivity.this, (int)button1.getX() + ":" + (int)button1.getY(), Toast.LENGTH_LONG).show();
Doc:
The visual x position of this view, in pixels.
For API below 11 you are on the right way: getTop() is the equivalent of getY() but without a possible animation/translation. getLeft() is the quivalent of getX() with the same restriction.
or
You can use View.getTop(), View.getBottom(), View.getLeft(), and View.getRight(). These will return the location of the top, bottom, left and right edge of the View relative to the parent.
or Use
View.getLocationOnScreen()
and/or
getLocationInWindow().
If you are using onTouch lister means use this one.
code for your onTouch method:
float screenX = v.getLeft() + event.getX(); // X in Screen Coordinates
float screenY = v.getTop() + event.getY(); // Y in Screen Coordinates
You have to wait until the View is measured, otherwise it will always return 0. Use an OnGlobalLayoutListener:
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int x = view.getLeft();
int y = view.getTop();
}
});
There are a lot of ways to get the coordinator position.
If you want to center a floating button such as a tutorial with tourguide library.
I suggest create this method
public Rect getRectFromAView(View view){
Rect rect=new Rect(); // create a new rect
view.getGlobalRect(rect);// draw the rect
return rect;
}
If I want to get the coordinate position of x or y
Rect rect=getREctFromAView(view);
rect.exactCenterX(); //Return the position X
rect.exactCenterY(); //Return the position Y
This is the case when I try to get the center position of a view.
try :-
float x = button.getX();
float y = button.getY();
I trying to get x,y for any object inside the layout but I got this values when object at end corner of the screen :
Object X : 266
Object Y : 361
Screen Width : 320
Screen Height: 480
how can I know where is the object exactly for the screen? (end,top,left,center).
Hope this helps..
public Rect locateView(View view) {
Rect loc = new Rect();
int[] location = new int[2];
if (view == null) {
return loc;
}
view.getLocationOnScreen(location);
loc.left = location[0];
loc.top = location[1];
loc.right = loc.left + view.getWidth();
loc.bottom = loc.top + view.getHeight();
return loc;
}
And I used the method this way:
Rect r = TVGridUtils.locateView(activity.findViewById(R.id.imageview));
float touchX=r.left+((r.right-r.left)/2);
float touchY=(r.bottom);
Note: I had to get the middle point of the imageview which i touched
I think you need to add the width and height of the objects to x and y values
To know where is the object exactly for the screen
X= 0,Y= 0 TOP LEFT
X= screenWidth-objectWidth,Y= 0 TOP RIGHT
X= 0,Y= screenHeight-objectHeight BOTTOM LEFT
X= screenWidth-objectWidth,Y= screenHeight-objectHeight BOTTOM RIGHT
Button b;
int x1 = b.getX();
int x2 = x1 + b.getWidth();
int y1 = b.getY();
int y2 = y1 + b.getHeight();
is it possible to find the View that is displayed at a given absolute x/y pixel coord?
Edit: I found a suitable Solution that works great:
private View findViewByCoord(float x, float y){
TextView textView = null;
int[] location = new int[2];
int width = 0;
int height = 0;
for(int reference : cardReference){
textView = (TextView) findViewById(reference);
textView.getLocationOnScreen(location);
width = textView.getWidth();
height = textView.getHeight();
if(location[0] <= x && x <= (location[0] + width) && location[1] <= y && y <= (location[1] + height)){
Log.i("Test", "Card " + textView.getText() + " is pointed");
return textView;
}
}
return null;
}
Where cardReference is an array of integer to Resources (in my case 20 TextViews arranged in a 4 x 5 Matrix):
int[] cardReference = new int[]{R.id.card1_1, R.id.card1_2, R.id.card1_3, R.id.card1_4,
R.id.card2_1, R.id.card2_2, R.id.card2_3, R.id.card2_4,
R.id.card3_1, R.id.card3_2, R.id.card3_3, R.id.card3_4,
R.id.card4_1, R.id.card4_2, R.id.card4_3, R.id.card4_4,
R.id.card5_1, R.id.card5_2, R.id.card5_3, R.id.card5_4};
To speed up performance i would consider to use an array of TextViews then call findViewById() in every Loop.
One 'solution' would be to loop through the parent view's children and check the getLeft() and getTop() coordinates against the X and Y coordinates of your choice. If there is a match, you have your view.
I'd like to hear other alternatives though.
Edit: You'd also have to work out the height/width of the view too in relation to the left and top coordinates given to see if your coordinates are within that range.