我想做的是在ImageView
上对尺寸和位置的变化进行动画处理。为此,我使用以下方法:
void doAnimation() {
ImageView logo = findViewById(R.id.logo);
float scaleVal = R.attr.actionBarSize / logo.getHeight(); // Finds the scale needed to make the logo as tall as the actionBar
// Gets the width and height in dp
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float density = getResources().getDisplayMetrics().density;
float dpH = displayMetrics.heightPixels / density;
float dpW = displayMetrics.widthPixels / density;
// The final X and Y in dp
float finalX = dpW - (logo.getWidth() / density) - 16;
float finalY = dpH - (logo.getHeight() / density) - 16;
// The final X and Y converted to %
float finalXPercentage = finalX / dpW;
float finalYPercentage = finalY / dpH;
logo.animate()
.setDuration(750)
.scaleX(scaleVal)
.scaleY(scaleVal)
.translationX(finalXPercentage)
.translationY(finalYPercentage);
}
我正在从 onResume()
方法调用 doAnimation()
方法,但由于显而易见的原因,我无法使用 getHeight()
或在 onResume()
方法中使用 getWidth()
。
问题是我不知道 Logo 的高度或宽度,因为我使用的是 ConstraintLayout
,因此我没有指定宽度或高度。我想做的是将 ImageView
移动到右上角(与其相距 16dp 的空间)并将其大小调整为与 ActionBar(工具栏)高度一样高。
最佳答案
您可以在 onLayoutChange
中尝试一下吗?我这样解决了我的问题。
logo.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
mLayout.removeOnLayoutChangeListener(this);
doyourAnimationcodehere();
}
});
关于java - 当您不知道 View 的尺寸时如何移动 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733597/