Reputation: 484
I have two ImageView
s. I want to move one to on top of the other.
When I try to retrieve the value of one of the ImageView
s position to move the other to it I get 0 on both x and y.
I have tried using getLeft
/getTop
, getX()
/getY()
, and getPositionOnScreen()
; They all return 0. Both views are inside of the same constraint layout.
XML of ImageView
returning 0:
<ImageView
android:id="@+id/playerOneCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="64dp"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="@+id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="@drawable/card" />
Code to return position:
int x = playerOneCardMove.getLeft();
int y = playerOneCardMove.getTop();
I have also used the following:
int x = playerOneCardMove.getX();
int y = playerOneCardMove.getY();
and:
int[] imageCoordinates = new int[2];
playerOneCard.getLocationOnScreen(imageCoordinates);
int x = imageCoordinates[0];
int y = imageCoordinates[1];
Code that executes onClick
to move the card:
public void transitionPlayerOne() {
int x = playerOneCard.getLeft();
int y = playerOneCard.getTop();
TranslateAnimation animation =
new TranslateAnimation(Animation.ABSOLUTE, x, Animation.ABSOLUTE, y);
animation.setDuration(1000); // animation duration
animation.setFillAfter(true);
playerOneCardMove.startAnimation(animation); // start animation
}
Upvotes: 2
Views: 3731
Reputation: 4060
When are you trying to get the X and Y of the ImageViews? If you are doing it straight in onCreate
(or some other place that the views are currently being laid), their x and y will be zero since they have not been laid out.
In this case, You have 2 options:
View.post { }
and do what you are doing in the callback.OnGlobalLayoutListener
like below.imageview.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// do something about the view's x and y.
// also don't forget to remove this OnGlobalLayoutListener using
// removeOnGlobalLayoutListener in here.
}
});
Upvotes: 6