我有两个ImageView
。我想将一个移到另一个之上。
当我尝试检索ImageView
s 位置之一的值以将另一个移动到它时,我在 x 和 y 上都得到 0。
我曾尝试使用getLeft
/ getTop
、getX()
/getY()
和getPositionOnScreen()
; 它们都返回 0。两个视图都在同一个约束布局内。
ImageView
返回 0 的XML :
<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" />
Run Code Online (Sandbox Code Playgroud)
返回位置的代码:
int x = playerOneCardMove.getLeft();
int y = playerOneCardMove.getTop();
Run Code Online (Sandbox Code Playgroud)
我还使用了以下内容:
int x = playerOneCardMove.getX();
int y = playerOneCardMove.getY();
Run Code Online (Sandbox Code Playgroud)
和:
int[] imageCoordinates = new int[2];
playerOneCard.getLocationOnScreen(imageCoordinates);
int x = imageCoordinates[0];
int y = imageCoordinates[1];
Run Code Online (Sandbox Code Playgroud)
执行onClick
移动卡片的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
你什么时候试图获得 ImageViews 的 X 和 Y?如果您直接在onCreate
(或当前正在放置视图的其他地方)进行操作,则它们的 x 和 y 将为零,因为它们尚未放置。
在这种情况下,您有 2 个选择:
View.post { }
在回调中使用并执行您正在执行的操作。OnGlobalLayoutListener
如下。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.
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2773 次 |
最近记录: |