我要做的是制作尺寸和尺寸的动画。 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);
}
我从doAnimation()
方法调用onResume()
方法,但由于显而易见的原因,我无法在getHeight()
方法中使用getWidth()
或onResume()
问题是我不知道徽标的高度或宽度,因为我正在使用ConstraintLayout
,因此我没有指定宽度或高度。我想要做的是将ImageView
移动到右上角(距离它有16dp的空间)并将其调整为与ActionBar(工具栏)高度一样高。
答案 0 :(得分:2)
你能否在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();
}
});
答案 1 :(得分:0)
您可以尝试使用View.Post()
void doAnimation() {
ImageView logo = findViewById(R.id.logo);
// new Runnable() can be substituted with () -> if you are using Java 8
logo.post(new Runnable() {
@Override
public void run() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float density = getResources().getDisplayMetrics().density;
// Finds the scale needed to make the logo as tall as the actionBar
float scaleVal = 56 / (logo.getHeight() / density);
// Gets the width and height in dp
float width = displayMetrics.widthPixels / density;
float height = displayMetrics.heightPixels;
// The final X and Y in dp
float finalX = logo.getX() + width / 2;
logo.animate()
.setDuration(ANIMATION_DURATION)
.scaleX(scaleVal).scaleY(scaleVal)
.xBy(finalX).y(0);
}
});
}