2012-03-09 7 views
7

Me gustaría hacer lo siguiente. Tengo un conjunto de botones que tienen algunos íconos. Cuando el usuario toca uno, me gustaría introducir una nueva Vista que comience en la misma coordenada que el icono tocado, y luego esa nueva Vista se moverá a alguna otra ubicación en la pantalla y cuando llegue allí se eliminará.¿Cuál es la forma correcta de animar una vista de una coordenada a otra?

Sé cómo crear una nueva vista y agregarla/eliminarla al RelativeLayout padre (¿no debería ser un RelativeLayout?) Y todo eso. Lo que no tengo claro es cómo obtener las coordenadas absolutas del botón que se pulsó (dado que es solo un elemento dentro de un diseño principal, dentro de otro diseño principal) y luego establecer sus coordenadas y aplicar una animación, y entonces ¿qué haría? notificarme que ha llegado a donde iba, para que pueda eliminarlo?

No se puede encontrar un ejemplo de cómo hacer esto de todos modos, por lo tanto, esperando que alguien pueda señalarme en la dirección correcta.

+0

bien, me he dado cuenta que a mí mismo, si no se interviene con una respuesta, voy a publicar mañana, para que otros puedan referencia. –

+0

¿Tiene un tutorial para esto también? – ManishSB

Respuesta

10

Por lo tanto, resulta que esto es mucho más directo de lo que imaginaba.

Creé un RelativeLayout a pantalla completa que solo se muestra mientras la animación está sucediendo.

tengo la posición de partida de mi botón enterrado como esto (que es divertido ver a estos mecanismos de codificación estilo C en Java, que son bastante raro en estos días:

int fromLoc[] = new int[2]; 
v.getLocationOnScreen(fromLoc);  
float startX = fromLoc[0]; 
float startY = fromLoc[1]; 

lo tanto, ahora tengo mi partida punto.

Mi punto final es una coordenada absoluta en la pantalla, puede asignar que sin embargo deseo

Entonces hago una pequeña clase de ayuda animaciones que me permite superar todas las coordenadas, la devolución de llamada, y el duración de la animación

public class Animations { 
public Animation fromAtoB(float fromX, float fromY, float toX, float toY, AnimationListener l, int speed){ 


     Animation fromAtoB = new TranslateAnimation(
       Animation.ABSOLUTE, //from xType 
       fromX, 
       Animation.ABSOLUTE, //to xType 
       toX, 
       Animation.ABSOLUTE, //from yType 
       fromY, 
       Animation.ABSOLUTE, //to yType 
       toY 
       ); 

     fromAtoB.setDuration(speed); 
     fromAtoB.setInterpolator(new AnticipateOvershootInterpolator(1.0f)); 


     if(l != null) 
      fromAtoB.setAnimationListener(l);    
       return fromAtoB; 
    } 
} 

y necesitamos un oyente para hacernos saber cuando la animación se realiza para desactivarla

AnimationListener animL = new AnimationListener() { 

     @Override 
     public void onAnimationStart(Animation animation) {  
     } 

     @Override 
     public void onAnimationRepeat(Animation animation) {   
     } 

     @Override 
     public void onAnimationEnd(Animation animation) { 
      //this is just a method to delete the ImageView and hide the animation Layout until we need it again. 
      clearAnimation();  
     } 
    }; 

Y por último lo tiramos todos juntos y presiona Ir

int fromLoc[] = new int[2]; 
    v.getLocationOnScreen(fromLoc);  
    float startX = fromLoc[0]; 
    float startY = fromLoc[1];  
    RelativeLayout rl = ((RelativeLayout)findViewById(R.id.sticker_animation_layout)); 
    ImageView sticker = new ImageView(this); 

    int stickerId = getStickerIdFromButton(v); 
    if(stickerId == 0){ 
     stickerAnimationPlaying = false; 
     return;   
    } 

    float destX = 200.0f;//arbitrary place on screen 
    float destY = 200.0f;//arbitrary place on screen 

    sticker.setBackgroundResource(stickerId); 
    sticker.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

    rl.addView(sticker); 
    Animations anim = new Animations(); 
    Animation a = anim.fromAtoB(startX, startY, destX, destY, animL,750); 
    sticker.setAnimation(a); 
    a.startNow(); 
+0

¿Tiene un tutorial para esto, para que me ayude, – ManishSB

+2

@ Real_steel4819, lo siento amigo, no tengo un tutorial ...solo las cosas que escribí en esta respuesta –

+0

¿Qué es 'getStickerIdFromButton (v);'? –

0

soy solo agregue mi vista en la posición central en el diseño del marco y traslade mi vista al eje xy al eje y. Pruebe a continuación código: -

Agregar vista de la imagen en FrameLayout

imgHeart = new ImageView(getBaseContext()); 
    imgHeart.setId(R.id.heartImage); 
    imgHeart.setImageResource(R.drawable.material_heart_fill_icon); 
    imgHeart.setLayoutParams(new FrameLayout.LayoutParams(50, 50, Gravity.CENTER)); 
    mainFrameLaout.addView(imgHeart); 

Añadir animación en vista de la imagen

 imgHeart.animate() 
      .scaleXBy(6) 
      .scaleYBy(6) 
      .setDuration(700) 
      .alpha(2) 
      .setListener(new Animator.AnimatorListener() { 
       @Override 
       public void onAnimationStart(Animator animation) { 

       } 

       @Override 
       public void onAnimationEnd(Animator animation) { 
        imgHeart.animate() 
          .scaleXBy(-6f).scaleYBy(-6f) 
          .alpha(.1f) 
          .translationX((heigthAndWidth[0]/2) - minusWidth) 
          .translationY(-((heigthAndWidth[1]/2) - minusHeight)) 
          .setDuration(1000) 
          .setListener(new Animator.AnimatorListener() { 
           @Override 
           public void onAnimationStart(Animator animation) { 
           } 

           @Override 
           public void onAnimationEnd(Animator animation) { 
           // remove image view from framlayout 
           } 
           @Override 
           public void onAnimationCancel(Animator animation) { 
           } 

           @Override 
           public void onAnimationRepeat(Animator animation) { 
           } 
          }).start(); 
       } 

       @Override 
       public void onAnimationCancel(Animator animation) { 

       } 

       @Override 
       public void onAnimationRepeat(Animator animation) { 

       } 
      }).start(); 
Cuestiones relacionadas