Resizing layouts programmatically (as animation)
I wrote a ResizeAnimation for a similar purpose. It's simple but costly.
Java
/**
* an animation for resizing the view.
*/
public class ResizeAnimation extends Animation {
private View mView;
private float mToHeight;
private float mFromHeight;
private float mToWidth;
private float mFromWidth;
public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) {
mToHeight = toHeight;
mToWidth = toWidth;
mFromHeight = fromHeight;
mFromWidth = fromWidth;
mView = v;
setDuration(300);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float height =
(mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth;
LayoutParams p = mView.getLayoutParams();
p.height = (int) height;
p.width = (int) width;
mView.requestLayout();
}
}
Kotlin
class ResizeAnimation(
private val view: View,
private val toHeight: Float,
private val fromHeight: Float,
private val toWidth: Float,
private val fromWidth: Float,
duration: Long
) : Animation() {
init {
this.duration = duration
}
override fun applyTransformation(
interpolatedTime: Float,
t: Transformation?
) {
val height = (toHeight - fromHeight) * interpolatedTime + fromHeight
val width = (toWidth - fromWidth) * interpolatedTime + fromWidth
val layoutParams = view.layoutParams
layoutParams.height = height.toInt()
layoutParams.width = width.toInt()
view.requestLayout()
}
}
On Honeycomb (Android 3.0) there is the Animator
and ObjectAnimator
classes for smoother animations.
Read it here
Example on how to animate the move of a view group (LinearLayout) with a bounce interpolator.
BounceInterpolator bounceInterpolator = new BounceInterpolator();
ObjectAnimator anim = ObjectAnimator.ofFloat(myViewGroup, "translationY", 0f, -200 );
anim.setInterpolator(bounceInterpolator);
anim.setDuration(1100).start();
This will trigger a smooth animation with a bounce effect and really move the views not like animation prior to Honeycomb. From the docs :
The previous animations changed the visual appearance of the target objects... but they didn't actually change the objects themselves.
Also you can resize with Google's new Spring animations.
SpringAnimation creation method:
fun getSpringAnimation(view: View, springAnimationType: FloatPropertyCompat<View>, finalPosition: Float): SpringAnimation {
val animation = SpringAnimation(view, springAnimationType )
// create a spring with desired parameters
val spring = SpringForce()
spring.finalPosition = finalPosition
spring.stiffness = SpringForce.STIFFNESS_VERY_LOW // optional
spring.dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY // optional
// set your animation's spring
animation.spring = spring
return animation
}
Usage (Resize to 80% of the original view size.)
getSpringAnimation(view, SpringAnimation.SCALE_X, 0.8f).start()
getSpringAnimation(view, SpringAnimation.SCALE_Y, 0.8f).start()