Android se desvanece y se desvanece con ImageView
Estoy teniendo algunos problemas con un pase de diapositivas que estoy construyendo.
He creado 2 animaciones en xml para fundido y fade out:
- Android: ¿Cómo iniciar una animación infinita aplicada en un ImageView después de la actividad con la vista animada se ha reanudado?
- OutOfMemoryError: Usando una imagen que es 1080 * 1920 haga la página de bienvenida
- ¿Cómo mantener múltiples capas de ImageViews y mantener su relación de aspecto basada en el más grande?
- Cómo hacer una imagen tan grande como sea posible, manteniendo la relación de aspecto
- Cambiar un icono en una entrada de Android ListView cuando se presiona
Fadein.xml
<?xml version="1.0" encoding="UTF-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="2000"/> </set>
Fadeout.xml
<?xml version="1.0" encoding="UTF-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="2000"/> </set>
Lo que Im'trying hacer, es cambiar las imágenes de un ImageView utilizando el efecto de fundido, por lo que la imagen actualmente se desvanecen, y otro se desvanecen. Teniendo en cuenta que tengo una imagen ya configurada, puedo fadeout esta imagen sin Problema, con esto:
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.your_fade_in_anim); imageView.startAnimation(fadeoutAnim);
Pero entonces, fijé la imagen siguiente a ser exhibida:
imageView.setImageBitmap(secondImage);
Simplemente aparece en la imageView, y cuando pongo la animación que oculta la imagen, se desvanece en … ¿Hay alguna manera de arreglar eso, quiero decir, cuando hago imageView.setImageBitmap (secondImage); , La imagen no se muestra inmediatamente, y sólo cuando el fundido en la animación se ejecuta?
- Android setX () y setY () comportándose de manera extraña
- Android, ImageView sobre ImageView
- Android: ¿Cómo puedo acelerar el desplazamiento de GridView?
- ¿Cómo puedo actualizar la imagen de fresco SimpleDraweeView, si se estableció una vez por setImageURI
- Animación panorámica de Android ImageView con scaleType centerCrop
- ListView haga clic para mostrar la imagen en ImageView
- Android - ¿Cómo posicionar la vista fuera de la pantalla?
- EditText afterTextChanged no funciona
Para implementar esto de la manera que ha comenzado, tendrá que agregar un AnimationListener para que pueda detectar el principio y el final de una animación. Cuando se llama onAnimationEnd () para el fade out, puede establecer la visibilidad de su objeto ImageView en View.INVISIBLE, cambiar las imágenes e iniciar su fade in animation – necesitará otro AnimationListener aquí también. Cuando reciba onAnimationEnd () para su animación de fundido, establezca el ImageView para que sea View.VISIBLE y que le dé el efecto que está buscando.
He implementado un efecto similar antes, pero he utilizado un ViewSwitcher con 2 ImageViews en lugar de un solo ImageView. Puede configurar las animaciones "in" y "out" para el ViewSwitcher con su fade in y fade out para que pueda administrar la implementación de AnimationListener. Entonces todo lo que necesitas hacer es alternar entre los 2 ImageViews.
Editar: Para ser un poco más útil, aquí está un ejemplo rápido de cómo utilizar ViewSwitcher. He incluido la fuente completa en https://github.com/aldryd/imageswitcher .
Activity_main.xml
<ViewSwitcher android:id="@+id/switcher" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:inAnimation="@anim/fade_in" android:outAnimation="@anim/fade_out" > <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/sunset" /> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitCenter" android:src="@drawable/clouds" /> </ViewSwitcher>
MainActivity.java
// Let the ViewSwitcher do the animation listening for you ((ViewSwitcher) findViewById(R.id.switcher)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ViewSwitcher switcher = (ViewSwitcher) v; if (switcher.getDisplayedChild() == 0) { switcher.showNext(); } else { switcher.showPrevious(); } } });
Quería lograr el mismo objetivo que tú, así que escribí el siguiente método que hace exactamente eso si se pasa un ImageView y una lista de referencias a dibujables de la imagen.
ImageView demoImage = (ImageView) findViewById(R.id.DemoImage); int imagesToShow[] = { R.drawable.image1, R.drawable.image2,R.drawable.image3 }; animate(demoImage, imagesToShow, 0,false); private void animate(final ImageView imageView, final int images[], final int imageIndex, final boolean forever) { //imageView <-- The View which displays the images //images[] <-- Holds R references to the images to display //imageIndex <-- index of the first image to show in images[] //forever <-- If equals true then after the last image it starts all over again with the first image resulting in an infinite loop. You have been warned. int fadeInDuration = 500; // Configure time values here int timeBetween = 3000; int fadeOutDuration = 1000; imageView.setVisibility(View.INVISIBLE); //Visible or invisible by default - this will apply when the animation ends imageView.setImageResource(images[imageIndex]); Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); // add this fadeIn.setDuration(fadeInDuration); Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setInterpolator(new AccelerateInterpolator()); // and this fadeOut.setStartOffset(fadeInDuration + timeBetween); fadeOut.setDuration(fadeOutDuration); AnimationSet animation = new AnimationSet(false); // change to false animation.addAnimation(fadeIn); animation.addAnimation(fadeOut); animation.setRepeatCount(1); imageView.setAnimation(animation); animation.setAnimationListener(new AnimationListener() { public void onAnimationEnd(Animation animation) { if (images.length - 1 > imageIndex) { animate(imageView, images, imageIndex + 1,forever); //Calls itself until it gets to the end of the array } else { if (forever){ animate(imageView, images, 0,forever); //Calls itself to start the animation all over again in a loop if forever = true } } } public void onAnimationRepeat(Animation animation) { // TODO Auto-generated method stub } public void onAnimationStart(Animation animation) { // TODO Auto-generated method stub } }); }
¿Ha pensado en utilizar TransitionDrawable en lugar de animaciones personalizadas? https://developer.android.com/reference/android/graphics/drawable/TransitionDrawable.html
Una forma de lograr lo que buscas es:
// create the transition layers Drawable[] layers = new Drawable[2]; layers[0] = new BitmapDrawable(getResources(), firstBitmap); layers[1] = new BitmapDrawable(getResources(), secondBitmap); TransitionDrawable transitionDrawable = new TransitionDrawable(layers); imageView.setImageDrawable(transitionDrawable); transitionDrawable.startTransition(FADE_DURATION);
Basado en la solución de Aladin Q, he aquí una función de ayuda que escribí, que cambiará la imagen en una vista de imagen mientras se ejecuta un poco de fade out / fade en la animación:
public static void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) { final Animation anim_out = AnimationUtils.loadAnimation(c, android.R.anim.fade_out); final Animation anim_in = AnimationUtils.loadAnimation(c, android.R.anim.fade_in); anim_out.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { v.setImageBitmap(new_image); anim_in.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) {} }); v.startAnimation(anim_in); } }); v.startAnimation(anim_out); }
Utilicé la animación usada de fadeIn para substituir la nueva imagen para la vieja
ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();
Estoy utilizando este tipo de rutina para encadenar las animaciones mediante programación.
final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out); final Animation anim_in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); anim_out.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { //////////////////////////////////////// // HERE YOU CHANGE YOUR IMAGE CONTENT // //////////////////////////////////////// //ui_image.setImage... anim_in.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) {} }); ui_image.startAnimation(anim_in); } }); ui_image.startAnimation(anim_out);
La mejor y la manera más fácil, para mí fue esto ..
-> Simplemente cree un hilo con Handler que contenga sleep ().
private ImageView myImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1); Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein); myImageView.startAnimation(myFadeInAnimation); new Thread(new Runnable() { private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { Log.w("hendler", "recived"); Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout); myImageView.startAnimation(myFadeOutAnimation); myImageView.setVisibility(View.INVISIBLE); } }; @Override public void run() { try{ Thread.sleep(2000); // your fadein duration }catch (Exception e){ } handler.sendEmptyMessage(1); } }).start(); }
Usted puede hacerlo por dos punto simple y el cambio en su código
1.In su xml en anim carpeta de su proyecto, Establecer el fade in y fade out duración no igual
2.In usted clase de java antes del comienzo de la animación del fundido hacia fuera, fije la segunda visibilidad de la imagenVeida entonces después de desvanecimiento hacia fuera la animación comenzó fijó la segunda visibilidad del imageView que usted desea encenderse visible
Fadeout.xml
<alpha android:duration="4000" android:fromAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:toAlpha="0.0" />
Fadein.xml
<alpha android:duration="6000" android:fromAlpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:toAlpha="1.0" />
En tu clase java
Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out); ImageView iv = (ImageView) findViewById(R.id.imageView1); ImageView iv2 = (ImageView) findViewById(R.id.imageView2); iv.setVisibility(View.VISIBLE); iv2.setVisibility(View.GONE); animFadeOut.reset(); iv.clearAnimation(); iv.startAnimation(animFadeOut); Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in); iv2.setVisibility(View.VISIBLE); animFadeIn.reset(); iv2.clearAnimation(); iv2.startAnimation(animFadeIn);
- El tamaño de fuente diferente de las cadenas en el mismo TextView
- Mala calidad de imagen después de cambiar el tamaño / escala de mapa de bits