2010-12-26 15 views
9

Como por objeto, reproduciría el efecto de fundido entre dos diseños. Ahora tengo esta situación:Efecto de desvanecimiento entre diseños

LinearLayout l; 
LinearLayout l2; 

para cambiar entre ellos he utilizado

l.setVisibility(View.GONE); 
l2.setVisibility(View.VISIBLE); 

Quiero añadir efecto de fundido entre esta transiction, ¿cómo puedo hacerlo?

Respuesta

3

Usando R.anim.fade_out & .R.anim.fade_in puede crear una animación que hace esto. No sé mucho sobre esto yo mismo, pero aquí hay un tutorial sobre animaciones en Android: Animation Tutorial

P.S. Este tutorial no es mío, por lo tanto, el crédito no me llega.

Editar:

AnimationSet set = new AnimationSet(true); 

Animation animation = new AlphaAnimation(0.0f, 1.0f); 
animation.setDuration(50); 
set.addAnimation(animation); 

animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f, 
Animation.RELATIVE_TO_SELF, -1.0f,Animation.RELATIVE_TO_SELF, 0.0f 
); 
animation.setDuration(100); 
set.addAnimation(animation); 

LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f); 
l.setLayoutAnimation(controller); 

Fundido de salida Animación

public static Animation runFadeOutAnimationOn(Activity ctx, View target) { 
    Animation animation = AnimationUtils.loadAnimation(ctx,android.R.anim.fade_out); 
    target.startAnimation(animation); 
    return animation; 
} 

supongo que puede intentar algo como esto, yo copia pegada la animación desde el tutorial no sé lo que hace exactamente como no tengo experiencia con el desarrollo de Android. Otro ejemplo podría ser Example 2

+1

Quiero usar android.R.anim.fade_in y fade_out y he leído algo sobre el método que invalidaPendingTransiction. Pero no entiendo cómo configurar la animación en LinearLayout. ¿Me puedes ayudar? – CeccoCQ

+0

El tutorial cubre anim.fade_in y fade_out, si te desplazas hacia abajo abit puedes ver el código de ejemplo. Esto debería ponerte en marcha, creo. – Citroenfris

21

Aquí está una solución de trabajo para cruzar fundido entre 2 diseños:

public class CrossFadeActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.crossfade); 

    final View l1 = findViewById(R.id.l1); 
    final View l2 = findViewById(R.id.l2); 

    final Animation fadeOut = AnimationUtils.loadAnimation(CrossFadeActivity.this, R.anim.fade_out); 
    final Animation fadeIn = AnimationUtils.loadAnimation(CrossFadeActivity.this, R.anim.fade_in); 

    findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      fadeOut.setAnimationListener(new AnimationListener() { 
       @Override 
       public void onAnimationStart(Animation animation) { 
       } 

       @Override 
       public void onAnimationRepeat(Animation animation) { 
       } 

       @Override 
       public void onAnimationEnd(Animation animation) { 
        l1.setVisibility(View.GONE); 
       } 
      }); 
      l1.startAnimation(fadeOut); 
      l2.setVisibility(View.VISIBLE); 
      l2.startAnimation(fadeIn); 
     } 
    }); 
    findViewById(R.id.button2).setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      fadeOut.setAnimationListener(new AnimationListener() { 
       @Override 
       public void onAnimationStart(Animation animation) { 
       } 

       @Override 
       public void onAnimationRepeat(Animation animation) { 
       } 

       @Override 
       public void onAnimationEnd(Animation animation) { 
        l2.setVisibility(View.GONE); 
       } 
      }); 
      l2.startAnimation(fadeOut); 
      l1.setVisibility(View.VISIBLE); 
      l1.startAnimation(fadeIn); 
     } 
    }); 
} 
} 

crossfade.xml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<LinearLayout 
    android:id="@+id/l1" 
    android:layout_width="fill_parent" 
    android:layout_height="300dip" 
    android:orientation="vertical" 
    android:background="@drawable/someimage" 
    > 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 

</LinearLayout> 

<RelativeLayout 
    android:id="@+id/l2" 
    android:layout_width="fill_parent" 
    android:layout_height="300dip" 
    android:orientation="vertical" 
    android:background="@drawable/someimage2" 
    android:visibility="gone" 
    > 

    <Button 
     android:id="@+id/button2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" 
     android:layout_centerInParent="true" 
     /> 

</RelativeLayout> 

</RelativeLayout> 

Donde L1 y L2 son 2 Ejemplo diseños aleatorios. El truco consiste en ponerlos en XML de modo que se superpongan entre sí (por ejemplo, en RelativeLayout) con visible/gone, agregar oyentes a las animaciones para alternar la visibilidad al finalizar, y establecer la vista que tiene que desvanecerse para ser visible antes del la animación comienza; de lo contrario, la animación no estará visible.

Pongo los botones con los oyentes para alternar la animación en los diseños en sí, porque necesito implementarlo de esa manera pero el oyente de clic puede estar en otra parte (si es solo uno debe usarse en combinación con alguna bandera o cheque para saber cómo alternar).

Estos son los archivos de animación. Ellos tienen que ser almacenados en la carpeta res/anim:

fade_in.xml

<?xml version="1.0" encoding="UTF-8"?> 
<alpha xmlns:android="http://schemas.android.com/apk/res/android" 
android:duration="1000" 
android:fillAfter="true" 
android:fromAlpha="0.0" 
android:toAlpha="1.0" /> 

fade_out.xml

<?xml version="1.0" encoding="UTF-8"?> 
<alpha xmlns:android="http://schemas.android.com/apk/res/android" 
android:duration="1000" 
android:fillAfter="true" 
android:fromAlpha="1.0" 
android:toAlpha="0" /> 

ACTUALIZACIÓN:

En lugar de utilizar R.anim.fade_in, puede usar el fade_in predeterminado de Android API (android.R.fade_in):

final Animation fadeIn = AnimationUtils.loadAnimation(CrossFadeActivity.this, android.R.anim.fade_in); 

Usando android.R.anim.fade_in, no necesitará crear el archivo res/anim/fade_in.xml.

Android tiene un paquete con algunas animaciones útiles en android.R.anim: http://developer.android.com/reference/android/R.anim.html

+2

También puede usar el método '.bringToFront()' para invertir el orden z de los diseños relativos en caso de que el usuario necesite interactuar con el primer plano. Esta respuesta solo cubre el aspecto de la animación. –

2

Dado que Android 3.0 se puede utilizar

android:animateLayoutChanges="true" 

en un diseño en XML y cualquier cambio a este contenido diseños específicos en tiempo de ejecución será animado. Por ejemplo, en su caso, tendrá que establecer este atributo para que el padre de la disposición de los padres de L y L2 por ejemplo

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context="me.kalem.android.RegistrationActivity" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:animateLayoutChanges="true" 
    android:padding="20dp"> 

    <LinearLayout 
     android:id="@+id/l1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:visibility="visible"> 

    ........ 

    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/l2" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:visibility="gone"> 

    ........ 

    </LinearLayout> 

</LinearLayout> 

L1 Ahora ocultar y mostrar L2 en tiempo de ejecución será animada.

Cuestiones relacionadas