Scale a view to another view's size using ValueAnimator
android, android-constraintlayout, java
Solution
Just add following method in your code.
private Animator getViewScaleAnimator(View from, final View target) {
// height resize animation
AnimatorSet animatorSet = new AnimatorSet();
int desiredHeight = from.getHeight();
int currentHeight = target.getHeight();
ValueAnimator heightAnimator = ValueAnimator.ofInt(currentHeight, desiredHeight);
heightAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) target.getLayoutParams();
params.height = (int) animation.getAnimatedValue();
target.setLayoutParams(params);
}
});
animatorSet.play(heightAnimator);
// width resize animation
int desiredWidth = from.getWidth();
int currentWidth = target.getWidth();
ValueAnimator widthAnimator = ValueAnimator.ofInt(currentWidth, desiredWidth);
widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) target.getLayoutParams();
params.width = (int) animation.getAnimatedValue();
target.setLayoutParams(params);
}
});
animatorSet.play(widthAnimator);
return animatorSet;
}
And call it on any event.( eg. click )
getViewScaleAnimator(fromView, targetView).setDuration(1000).start();
Here is an output.
Problem
I'm trying to resize a view to fit another view's size using a ValueAnimator. I'm using it instead of an Animation because I need the view to be clickable afterwards. ``` private Animator getHeightScaleAnimator(View target) { ConstraintLayout.LayoutParams thisParams = (ConstraintLayout.LayoutParams) getLayoutParams(); ConstraintLayout.LayoutParams targetParams = (ConstraintLayout.LayoutParams) target.getLayoutParams(); int currentHeight = thisParams.height; int desiredHeight = targetParams.height; ValueAnimator animator = ValueAnimator.ofInt(currentHeight, desiredHeight); animator.addUpdateListener(animation -> { int newInt = (int) animation.getAnimatedValue(); thisParams.width = newInt; invalidate(); requestLayout(); }); return animator; } ``` The above code shows a method in which I try to increase the view's height to the desired view's height, and I have the same method for the width, but with width instead of height. The desired behaviour was the view to increase it's size until it's as big as the target view, but for some odd reason, the view moves instead of resizing. The implementing class is an extension of ImageView, but no method from ImageView as changed. What can I possibly do to increase a view's size up to another view's size in an animated fashion?