property example changes animate android animation

example - Android: expandir/contraer animación



transition android (30)

Digamos que tengo un linearLayout vertical con:

[v1] [v2]

Por defecto v1 tiene visibily = GONE. Me gustaría mostrar v1 con una animación expandida y empujar hacia abajo v2 al mismo tiempo.

Probé algo como esto:

Animation a = new Animation() { int initialHeight; @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final int newHeight = (int)(initialHeight * interpolatedTime); v.getLayoutParams().height = newHeight; v.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); initialHeight = height; } @Override public boolean willChangeBounds() { return true; } };

Pero con esta solución, tengo un parpadeo cuando comienza la animación. Creo que es causada por v1 que muestra el tamaño completo antes de que se aplique la animación.

Con javascript, esta es una línea de jQuery! ¿Alguna forma sencilla de hacer esto con Android?


Aquí está mi solución. Creo que es más sencillo. Solo expande la vista pero se puede ampliar fácilmente.

public class WidthExpandAnimation extends Animation { int _targetWidth; View _view; public WidthExpandAnimation(View view) { _view = view; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime < 1.f) { int newWidth = (int) (_targetWidth * interpolatedTime); _view.layout(_view.getLeft(), _view.getTop(), _view.getLeft() + newWidth, _view.getBottom()); } else _view.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); _targetWidth = width; } @Override public boolean willChangeBounds() { return true; } }


Asegúrese de tener v1 configurado para tener una altura de diseño de cero justo antes de que comience la animación. Desea inicializar su configuración para que se vea como el primer cuadro de la animación antes de comenzar la animación.


Creo que la solución más sencilla es establecer android:animateLayoutChanges="true" en su LinearLayout y luego solo mostrar / ocultar la vista configurando su visibilidad. Funciona como un encanto, pero no tienes control sobre la duración de la animación


Estás en el camino correcto. Asegúrese de tener v1 configurado para tener una altura de diseño de cero justo antes de que comience la animación. Desea inicializar su configuración para que se vea como el primer cuadro de la animación antes de comenzar la animación.


Esta fue mi solución, mi ImageView crece del 100% al 200% y vuelve a su tamaño original, usando dos archivos de animación dentro de la carpeta res/anim/

anim_grow.xml

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <scale android:fromXScale="1.0" android:toXScale="2.0" android:fromYScale="1.0" android:toYScale="2.0" android:duration="3000" android:pivotX="50%" android:pivotY="50%" android:startOffset="2000" /> </set>

anim_shrink.xml

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <scale android:fromXScale="2.0" android:toXScale="1.0" android:fromYScale="2.0" android:toYScale="1.0" android:duration="3000" android:pivotX="50%" android:pivotY="50%" android:startOffset="2000" /> </set>

Enviar un ImageView a mi método setAnimationGrowShrink()

ImageView img1 = (ImageView)findViewById(R.id.image1); setAnimationGrowShrink(img1);

setAnimationGrowShrink() :

private void setAnimationGrowShrink(final ImageView imgV){ final Animation animationEnlarge = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.anim_grow); final Animation animationShrink = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.anim_shrink); imgV.startAnimation(animationEnlarge); animationEnlarge.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { imgV.startAnimation(animationShrink); } }); animationShrink.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { imgV.startAnimation(animationEnlarge); } }); }


Este es un fragmento que usé para cambiar el tamaño del ancho de una vista (LinearLayout) con animación.

Se supone que el código se expande o se reduce según el tamaño de destino. Si desea un ancho de fill_parent, tendrá que pasar el .getMeasuredWidth principal como ancho de destino mientras configura el indicador como verdadero.

Espero que ayude a algunos de ustedes.

public class WidthResizeAnimation extends Animation { int targetWidth; int originaltWidth; View view; boolean expand; int newWidth = 0; boolean fillParent; public WidthResizeAnimation(View view, int targetWidth, boolean fillParent) { this.view = view; this.originaltWidth = this.view.getMeasuredWidth(); this.targetWidth = targetWidth; newWidth = originaltWidth; if (originaltWidth > targetWidth) { expand = false; } else { expand = true; } this.fillParent = fillParent; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (expand && newWidth < targetWidth) { newWidth = (int) (newWidth + (targetWidth - newWidth) * interpolatedTime); } if (!expand && newWidth > targetWidth) { newWidth = (int) (newWidth - (newWidth - targetWidth) * interpolatedTime); } if (fillParent && interpolatedTime == 1.0) { view.getLayoutParams().width = -1; } else { view.getLayoutParams().width = newWidth; } view.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; }

}


Esto es realmente simple con droidQuery . Para empezar, considera este diseño:

<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <LinearLayout android:id="@+id/v1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 1" /> </LinearLayout> <LinearLayout android:id="@+id/v2" android:layout_width="wrap_content" android:layout_height="0dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 2" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 3" /> </LinearLayout> </LinearLayout>

Podemos animar la altura al valor deseado, por ejemplo 100dp, utilizando el siguiente código:

//convert 100dp to pixel value int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());

Luego usa droidQuerypara animar. La forma más sencilla es con esto:

$.animate("{ height: " + height + "}", new AnimationOptions());

Para hacer que la animación sea más atractiva, considere agregar una suavización:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE));

También puede cambiar la duración del AnimationOptionsuso del duration()método, o manejar lo que sucede cuando finaliza la animación. Para un ejemplo complejo, intente:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE) .duration(1000) .complete(new Function() { @Override public void invoke($ d, Object... args) { $.toast(context, "finished", Toast.LENGTH_SHORT); } }));


La answer @Tom Esterez, pero actualizada para usar view.measure () correctamente para Android getMeasuredHeight devuelve valores incorrectos!

// http://easings.net/ Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f); public static Animation expand(final View view) { int matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY); int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(matchParentMeasureSpec, wrapContentMeasureSpec); final int targetHeight = view.getMeasuredHeight(); // Older versions of android (pre API 21) cancel animations for views with a height of 0 so use 1 instead. view.getLayoutParams().height = 1; view.setVisibility(View.VISIBLE); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { view.getLayoutParams().height = interpolatedTime == 1 ? ViewGroup.LayoutParams.WRAP_CONTENT : (int) (targetHeight * interpolatedTime); view.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; animation.setInterpolator(easeInOutQuart); animation.setDuration(computeDurationFromHeight(view)); view.startAnimation(animation); return animation; } public static Animation collapse(final View view) { final int initialHeight = view.getMeasuredHeight(); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime == 1) { view.setVisibility(View.GONE); } else { view.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime); view.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; a.setInterpolator(easeInOutQuart); int durationMillis = computeDurationFromHeight(view); a.setDuration(durationMillis); view.startAnimation(a); return a; } private static int computeDurationFromHeight(View view) { // 1dp/ms * multiplier return (int) (view.getMeasuredHeight() / view.getContext().getResources().getDisplayMetrics().density); }


Me encontré con el mismo problema hoy y supongo que la verdadera solución a esta pregunta es la siguiente.

<LinearLayout android:id="@+id/container" android:animateLayoutChanges="true" ... />

Tendrá que establecer esta propiedad para todos los diseños superiores, que están involucrados en el cambio. Si ahora configura la visibilidad de un diseño en GONE, el otro tomará el espacio a medida que el que desaparece lo está liberando. Habrá una animación predeterminada que es una especie de "desvanecimiento", pero creo que puedes cambiar esto, pero la última no la he probado, por ahora.


Me gustaría agregar algo a la muy útil respuesta de arriba . Si no conoce la altura con la que terminará ya que sus vistas .getHeight () devuelve 0, puede hacer lo siguiente para obtener la altura:

contentView.measure(DUMMY_HIGH_DIMENSION, DUMMY_HIGH_DIMENSION); int finalHeight = view.getMeasuredHeight();

Donde DUMMY_HIGH_DIMENSIONS es el ancho / alto (en píxeles) que su vista está restringida a ... tener un gran número es razonable cuando la vista está encapsulada con un ScrollView.


Ok, acabo de encontrar una solución MUY fea:

public static Animation expand(final View v, Runnable onEnd) { try { Method m = v.getClass().getDeclaredMethod("onMeasure", int.class, int.class); m.setAccessible(true); m.invoke( v, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(((View)v.getParent()).getMeasuredHeight(), MeasureSpec.AT_MOST) ); } catch (Exception e){ Log.e("test", "", e); } final int initialHeight = v.getMeasuredHeight(); Log.d("test", "initialHeight="+initialHeight); v.getLayoutParams().height = 0; v.setVisibility(View.VISIBLE); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final int newHeight = (int)(initialHeight * interpolatedTime); v.getLayoutParams().height = newHeight; v.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; a.setDuration(5000); v.startAnimation(a); return a; }

¡Siéntete libre de proponer una mejor solución!


Para una animación suave, use el controlador con el método de ejecución ... y disfrute de la animación Expandir / Contraer

class AnimUtils{ public void expand(final View v) { int ANIMATION_DURATION=500;//in milisecond v.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); final int targtetHeight = v.getMeasuredHeight(); v.getLayoutParams().height = 0; v.setVisibility(View.VISIBLE); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { v.getLayoutParams().height = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT : (int)(targtetHeight * interpolatedTime); v.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration(ANIMATION_DURATION); // a.setDuration((int)(targtetHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); } public void collapse(final View v) { final int initialHeight = v.getMeasuredHeight(); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if(interpolatedTime == 1){ v.setVisibility(View.GONE); }else{ v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime); v.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration(ANIMATION_DURATION); // a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); }

}

Y llame usando este código:

private void setAnimationOnView(final View inactive ) { //I am applying expand and collapse on this TextView ...You can use your view //for expand animation new Handler().postDelayed(new Runnable() { @Override public void run() { new AnimationUtililty().expand(inactive); } }, 1000); //For collapse new Handler().postDelayed(new Runnable() { @Override public void run() { new AnimationUtililty().collapse(inactive); //inactive.setVisibility(View.GONE); } }, 8000); }

Otra solución es:

public void expandOrCollapse(final View v,String exp_or_colpse) { TranslateAnimation anim = null; if(exp_or_colpse.equals("expand")) { anim = new TranslateAnimation(0.0f, 0.0f, -v.getHeight(), 0.0f); v.setVisibility(View.VISIBLE); } else{ anim = new TranslateAnimation(0.0f, 0.0f, 0.0f, -v.getHeight()); AnimationListener collapselistener= new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { v.setVisibility(View.GONE); } }; anim.setAnimationListener(collapselistener); } // To Collapse // anim.setDuration(300); anim.setInterpolator(new AccelerateInterpolator(0.5f)); v.startAnimation(anim); }


Sí, estoy de acuerdo con los comentarios anteriores. Y, de hecho, parece que lo correcto (o al menos lo más fácil) es especificar (en XML) una altura de diseño inicial de "0px", y luego puede pasar otro argumento para "toHeight" ( es decir, la "altura final") para el constructor de su subclase de animación personalizada, por ejemplo, en el ejemplo anterior, se vería algo así:

public DropDownAnim( View v, int toHeight ) { ... }

De todos modos, espero que ayude! :)


Si no desea expandirse o colapsarse en su totalidad, aquí hay un simple HeightAnimation:

import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; public class HeightAnimation extends Animation { protected final int originalHeight; protected final View view; protected float perValue; public HeightAnimation(View view, int fromHeight, int toHeight) { this.view = view; this.originalHeight = fromHeight; this.perValue = (toHeight - fromHeight); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime); view.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }

Uso:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight()); heightAnim.setDuration(1000); view.startAnimation(heightAnim);


Soluciones combinadas de @Tom Esterez y @Geraldo Neto.

public static void expandOrCollapseView(View v,boolean expand){ if(expand){ v.measure(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT); final int targetHeight = v.getMeasuredHeight(); v.getLayoutParams().height = 0; v.setVisibility(View.VISIBLE); ValueAnimator valueAnimator = ValueAnimator.ofInt(targetHeight); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(500); valueAnimator.start(); } else { final int initialHeight = v.getMeasuredHeight(); ValueAnimator valueAnimator = ValueAnimator.ofInt(initialHeight,0); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); if((int)animation.getAnimatedValue() == 0) v.setVisibility(View.GONE); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(500); valueAnimator.start(); } } //sample usage expandOrCollapseView((Your ViewGroup),(Your ViewGroup).getVisibility()!=View.VISIBLE);


Sumado a la excelente respuesta de Tom Esterez y la excelente actualización de Erik B, pensé en publicar mi propia opinión, compactando los métodos de expansión y contratación en uno solo. De esta manera, podrías por ejemplo tener una acción como esta ...

button.setOnClickListener(v -> expandCollapse(view));

... que llama al método a continuación y le permite saber qué hacer después de cada onClick () ...

public static void expandCollapse(View view) { boolean expand = view.getVisibility() == View.GONE; Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f); view.measure( View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) ); int height = view.getMeasuredHeight(); int duration = (int) (height/view.getContext().getResources().getDisplayMetrics().density); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (expand) { view.getLayoutParams().height = 1; view.setVisibility(View.VISIBLE); if (interpolatedTime == 1) { view.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; } else { view.getLayoutParams().height = (int) (height * interpolatedTime); } view.requestLayout(); } else { if (interpolatedTime == 1) { view.setVisibility(View.GONE); } else { view.getLayoutParams().height = height - (int) (height * interpolatedTime); view.requestLayout(); } } } @Override public boolean willChangeBounds() { return true; } }; animation.setInterpolator(easeInOutQuart); animation.setDuration(duration); view.startAnimation(animation); }


Tomé la solution @LenaYan que no me funcionó correctamente ( porque estaba transformando la Vista en una vista de altura 0 antes de colapsar y / o expandir ) e hice algunos cambios.

Ahora funciona bien , al tomar la altura anterior de la Vista y comenzar a expandir con este tamaño. El colapso es el mismo.

Simplemente puede copiar y pegar el siguiente código:

public static void expand(final View v, int duration, int targetHeight) { int prevHeight = v.getHeight(); v.setVisibility(View.VISIBLE); ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(duration); valueAnimator.start(); } public static void collapse(final View v, int duration, int targetHeight) { int prevHeight = v.getHeight(); ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(duration); valueAnimator.start(); }

Uso:

//Expanding the View expand(yourView, 2000, 200); // Collapsing the View collapse(yourView, 2000, 100);

¡Suficientemente fácil!

Gracias LenaYan por el código inicial!


Trataba de hacer lo que creo que era una animación muy similar y encontré una solución elegante. Este código supone que siempre vas desde 0-> h o h-> 0 (siendo h la altura máxima). Los tres parámetros del constructor son vista = la vista a animar (en mi caso, una vista web), targetHeight = la altura máxima de la vista y abajo = un valor booleano que especifica la dirección (verdadero = expandido, falso = colapsado).

public class DropDownAnim extends Animation { private final int targetHeight; private final View view; private final boolean down; public DropDownAnim(View view, int targetHeight, boolean down) { this.view = view; this.targetHeight = targetHeight; this.down = down; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newHeight; if (down) { newHeight = (int) (targetHeight * interpolatedTime); } else { newHeight = (int) (targetHeight * (1 - interpolatedTime)); } view.getLayoutParams().height = newHeight; view.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } }


Una alternativa es usar una animación de escala con los siguientes factores de escala para expandir:

ScaleAnimation anim = new ScaleAnimation(1, 1, 0, 1);

y para colapsar:

ScaleAnimation anim = new ScaleAnimation(1, 1, 1, 0);


Veo que esta pregunta se hizo popular, así que publico mi solución real. La principal ventaja es que no es necesario conocer la altura expandida para aplicar la animación y una vez que se amplía la vista, se adapta la altura si el contenido cambia. Funciona muy bien para mí.

public static void expand(final View v) { v.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); final int targetHeight = v.getMeasuredHeight(); // Older versions of android (pre API 21) cancel animations for views with a height of 0. v.getLayoutParams().height = 1; v.setVisibility(View.VISIBLE); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { v.getLayoutParams().height = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT : (int)(targetHeight * interpolatedTime); v.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); } public static void collapse(final View v) { final int initialHeight = v.getMeasuredHeight(); Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if(interpolatedTime == 1){ v.setVisibility(View.GONE); }else{ v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime); v.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; // 1dp/ms a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density)); v.startAnimation(a); }


Esta es una solución de trabajo adecuada, la he probado:

Explicar:

private void expand(View v) { v.setVisibility(View.VISIBLE); v.measure(View.MeasureSpec.makeMeasureSpec(PARENT_VIEW.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); final int targetHeight = v.getMeasuredHeight(); mAnimator = slideAnimator(0, targetHeight); mAnimator.setDuration(800); mAnimator.start(); }

Colapso:

private void collapse(View v) { int finalHeight = v.getHeight(); mAnimator = slideAnimator(finalHeight, 0); mAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { //Height=0, but it set visibility to GONE llDescp.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); mAnimator.start(); }

Animador de valores:

private ValueAnimator slideAnimator(int start, int end) { ValueAnimator mAnimator = ValueAnimator.ofInt(start, end); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { //Update Height int value = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = llDescp.getLayoutParams(); layoutParams.height = value; v.setLayoutParams(layoutParams); } }); return mAnimator; }

Vista v es la vista que se animará, PARENT_VIEW es la vista de contenedor que contiene la vista.


La mejor solución para expandir / contraer la vista:

@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { View view = buttonView.getId() == R.id.tb_search ? fSearch : layoutSettings; transform(view, 200, isChecked ? ViewGroup.LayoutParams.WRAP_CONTENT : 0); } public static void transform(final View v, int duration, int targetHeight) { int prevHeight = v.getHeight(); v.setVisibility(View.VISIBLE); ValueAnimator animator; if (targetHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); animator = ValueAnimator.ofInt(prevHeight, v.getMeasuredHeight()); } else { animator = ValueAnimator.ofInt(prevHeight, targetHeight); } animator.addUpdateListener(animation -> { v.getLayoutParams().height = (animation.getAnimatedFraction() == 1.0f) ? targetHeight : (int) animation.getAnimatedValue(); v.requestLayout(); }); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(duration); animator.start(); }


Utilice ValueAnimator:

ValueAnimator expandAnimation = ValueAnimator.ofInt(mainView.getHeight(), 400); expandAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { int height = (Integer) animation.getAnimatedValue(); RelativeLayout.LayoutParams lp = (LayoutParams) mainView.getLayoutParams(); lp.height = height; } }); expandAnimation.setDuration(500); expandAnimation.start();


Basándome en las soluciones de @Tom Esterez y @Seth Nelson (top 2) las simplifiqué. Además de las soluciones originales, no depende de las opciones del desarrollador (configuración de animación).

private void resizeWithAnimation(final View view, int duration, final int targetHeight) { final int initialHeight = view.getMeasuredHeight(); final int distance = targetHeight - initialHeight; Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime == 1 && targetHeight == 0) { view.setVisibility(View.GONE); } else { view.getLayoutParams().height = (int) (initialHeight + distance * interpolatedTime); view.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; a.setDuration(duration); view.startAnimation(a); }


Creé una versión en la que no es necesario especificar la altura del diseño, por lo que es mucho más fácil y limpio de usar. La solución es obtener la altura en el primer cuadro de la animación (está disponible en ese momento, al menos durante mis pruebas). De esta manera puede proporcionar una Vista con una altura y un margen inferior arbitrarios.

También hay un pequeño truco en el constructor: el margen inferior se establece en -10000 para que la vista se oculte antes de la transformación (evita el parpadeo).

public class ExpandAnimation extends Animation { private View mAnimatedView; private ViewGroup.MarginLayoutParams mViewLayoutParams; private int mMarginStart, mMarginEnd; public ExpandAnimation(View view) { mAnimatedView = view; mViewLayoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); mMarginEnd = mViewLayoutParams.bottomMargin; mMarginStart = -10000; //hide before viewing by settings very high negative bottom margin (hack, but works nicely) mViewLayoutParams.bottomMargin = mMarginStart; mAnimatedView.setLayoutParams(mViewLayoutParams); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); //view height is already known when the animation starts if(interpolatedTime==0){ mMarginStart = -mAnimatedView.getHeight(); } mViewLayoutParams.bottomMargin = (int)((mMarginEnd-mMarginStart) * interpolatedTime)+mMarginStart; mAnimatedView.setLayoutParams(mViewLayoutParams); } }


He adaptado la respuesta aceptada actualmente por Tom Esterez , que trabajó pero tenía una animación muy suave y entrecortado no. Básicamente, mi solución reemplaza a Animationcon a ValueAnimator, que puede equiparse con una Interpolatorde su elección para lograr diversos efectos, como sobrepasar, rebotar, acelerar, etc.

Esta solución funciona muy bien con vistas que tienen una altura dinámica (es decir, usando WRAP_CONTENT), ya que primero mide la altura requerida real y luego la anima a esa altura.

public static void expand(final View v) { v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); final int targetHeight = v.getMeasuredHeight(); // Older versions of android (pre API 21) cancel animations for views with a height of 0. v.getLayoutParams().height = 1; v.setVisibility(View.VISIBLE); ValueAnimator va = ValueAnimator.ofInt(1, targetHeight); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (Integer) animation.getAnimatedValue(); v.requestLayout(); } }); va.addListener(new Animator.AnimatorListener() { @Override public void onAnimationEnd(Animator animation) { v.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; } @Override public void onAnimationStart(Animator animation) {} @Override public void onAnimationCancel(Animator animation) {} @Override public void onAnimationRepeat(Animator animation) {} }); va.setDuration(300); va.setInterpolator(new OvershootInterpolator()); va.start(); } public static void collapse(final View v) { final int initialHeight = v.getMeasuredHeight(); ValueAnimator va = ValueAnimator.ofInt(initialHeight, 0); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (Integer) animation.getAnimatedValue(); v.requestLayout(); } }); va.addListener(new Animator.AnimatorListener() { @Override public void onAnimationEnd(Animator animation) { v.setVisibility(View.GONE); } @Override public void onAnimationStart(Animator animation) {} @Override public void onAnimationCancel(Animator animation) {} @Override public void onAnimationRepeat(Animator animation) {} }); va.setDuration(300); va.setInterpolator(new DecelerateInterpolator()); va.start(); }

Entonces simplemente llamas expand( myView );ocollapse( myView ); .


Puede usar un ViewPropertyAnimator con un ligero giro. Para contraer, escale la vista a una altura de 1 píxel, luego ocúltela. Para expandir, mostrarlo, luego expandirlo a su altura.

private void collapse(final View view) { view.setPivotY(0); view.animate().scaleY(1/view.getHeight()).setDuration(1000).withEndAction(new Runnable() { @Override public void run() { view.setVisibility(GONE); } }); } private void expand(View view, int height) { float scaleFactor = height / view.getHeight(); view.setVisibility(VISIBLE); view.setPivotY(0); view.animate().scaleY(scaleFactor).setDuration(1000); }

El pivote le dice a la vista desde dónde escalar, el valor predeterminado está en el medio. La duración es opcional (por defecto = 1000). También puede configurar el interpolador para utilizar, como.setInterpolator(new AccelerateDecelerateInterpolator())


/** * Animation that either expands or collapses a view by sliding it down to make * it visible. Or by sliding it up so it will hide. It will look like it slides * behind the view above. * */ public class FinalExpandCollapseAnimation extends Animation { private View mAnimatedView; private int mEndHeight; private int mType; public final static int COLLAPSE = 1; public final static int EXPAND = 0; private LinearLayout.LayoutParams mLayoutParams; private RelativeLayout.LayoutParams mLayoutParamsRel; private String layout; private Context context; /** * Initializes expand collapse animation, has two types, collapse (1) and * expand (0). * * @param view * The view to animate * @param type * The type of animation: 0 will expand from gone and 0 size to * visible and layout size defined in xml. 1 will collapse view * and set to gone */ public FinalExpandCollapseAnimation(View view, int type, int height, String layout, Context context) { this.layout = layout; this.context = context; mAnimatedView = view; mEndHeight = mAnimatedView.getMeasuredHeight(); if (layout.equalsIgnoreCase("linear")) mLayoutParams = ((LinearLayout.LayoutParams) view.getLayoutParams()); else mLayoutParamsRel = ((RelativeLayout.LayoutParams) view.getLayoutParams()); mType = type; if (mType == EXPAND) { AppConstant.ANIMATED_VIEW_HEIGHT = height; } else { if (layout.equalsIgnoreCase("linear")) mLayoutParams.topMargin = 0; else mLayoutParamsRel.topMargin = convertPixelsIntoDensityPixels(36); } setDuration(600); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime < 1.0f) { if (mType == EXPAND) { if (layout.equalsIgnoreCase("linear")) { mLayoutParams.height = AppConstant.ANIMATED_VIEW_HEIGHT + (-AppConstant.ANIMATED_VIEW_HEIGHT + (int) (AppConstant.ANIMATED_VIEW_HEIGHT * interpolatedTime)); } else { mLayoutParamsRel.height = AppConstant.ANIMATED_VIEW_HEIGHT + (-AppConstant.ANIMATED_VIEW_HEIGHT + (int) (AppConstant.ANIMATED_VIEW_HEIGHT * interpolatedTime)); } mAnimatedView.setVisibility(View.VISIBLE); } else { if (layout.equalsIgnoreCase("linear")) mLayoutParams.height = mEndHeight - (int) (mEndHeight * interpolatedTime); else mLayoutParamsRel.height = mEndHeight - (int) (mEndHeight * interpolatedTime); } mAnimatedView.requestLayout(); } else { if (mType == EXPAND) { if (layout.equalsIgnoreCase("linear")) { mLayoutParams.height = AppConstant.ANIMATED_VIEW_HEIGHT; mLayoutParams.topMargin = 0; } else { mLayoutParamsRel.height = AppConstant.ANIMATED_VIEW_HEIGHT; mLayoutParamsRel.topMargin = convertPixelsIntoDensityPixels(36); } mAnimatedView.setVisibility(View.VISIBLE); mAnimatedView.requestLayout(); } else { if (layout.equalsIgnoreCase("linear")) mLayoutParams.height = 0; else mLayoutParamsRel.height = 0; mAnimatedView.setVisibility(View.GONE); mAnimatedView.requestLayout(); } } } private int convertPixelsIntoDensityPixels(int pixels) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return (int) metrics.density * pixels; } }

La clase se puede llamar de la siguiente manera.

if (findViewById(R.id.ll_specailoffer_show_hide).getVisibility() == View.VISIBLE) { ((ImageView) findViewById(R.id.iv_specialhour_seemore)).setImageResource(R.drawable.white_dropdown_up); FinalExpandCollapseAnimation finalExpandCollapseAnimation = new FinalExpandCollapseAnimation( findViewById(R.id.ll_specailoffer_show_hide), FinalExpandCollapseAnimation.COLLAPSE, SpecialOfferHeight, "linear", this); findViewById(R.id.ll_specailoffer_show_hide) .startAnimation(finalExpandCollapseAnimation); ((View) findViewById(R.id.ll_specailoffer_show_hide).getParent()).invalidate(); } else { ((ImageView) findViewById(R.id.iv_specialhour_seemore)).setImageResource(R.drawable.white_dropdown); FinalExpandCollapseAnimation finalExpandCollapseAnimation = new FinalExpandCollapseAnimation( findViewById(R.id.ll_specailoffer_show_hide), FinalExpandCollapseAnimation.EXPAND, SpecialOfferHeight, "linear", this); findViewById(R.id.ll_specailoffer_show_hide) .startAnimation(finalExpandCollapseAnimation); ((View) findViewById(R.id.ll_specailoffer_show_hide).getParent()).invalidate(); }


public static void expand(final View v, int duration, int targetHeight) { v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); v.getLayoutParams().height = 0; v.setVisibility(View.VISIBLE); ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(duration); valueAnimator.start(); } public static void collapse(final View v, int duration, int targetHeight) { ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { v.getLayoutParams().height = (int) animation.getAnimatedValue(); v.requestLayout(); } }); valueAnimator.setInterpolator(new DecelerateInterpolator()); valueAnimator.setDuration(duration); valueAnimator.start(); }


public static void slide(View v, int speed, int pos) { v.animate().setDuration(speed); v.animate().translationY(pos); v.animate().start(); } // slide down slide(yourView, 250, yourViewHeight); // slide up slide(yourView, 250, 0);