Activate an event when it’s moving

Asked

Viewed 49 times

2

I have a ImageView moving on the screen, I need to perform an animation when it is touched by the user, but image.setOnClickListener and also image.onTouchListener are not being activated when the image is clicked.

res/anim/Translate.xml

<?xml version="1.0" encoding="utf-8"?>

<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/decelerate_quad"
    android:fromXDelta="-100%"
    android:toXDelta="0%"
    android:fromYDelta="0%"
    android:toYDelta="0%"
    android:duration="2000"
    android:zAdjustment="top" />

Activity that contains the start of the animation

private void IniciarAnimacoes() {

    //Animaçoes dos pinguins
    anim = AnimationUtils.loadAnimation(this, R.anim.movimento_pinguim);
    anim.reset();

    imgPiguim = (ImageView) findViewById(R.id.imgPinguim);
    imgPiguim.setBackgroundResource(R.drawable.background_pinguim_anima);
    animaPiguim = (AnimationDrawable)imgPiguim.getBackground();
    imgPiguim.clearAnimation();
    imgPiguim.startAnimation(anim);

In the code the penguin keeps jumping on the screen, I need that when the user touches it sometime trigger an event.

Could someone help me with this, with some example or what other parameters should be used?

1 answer

0

In the method onCreate() get a reference to Imageview and assign it a onClickListener:

    imgPiguim = (ImageView) findViewById(R.id.imgPinguim);

    imgPiguim.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Código a ser executado quando a imagem for clicada
            Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
        }
    });

In the method onClick() put the code that should be executed when the image is clicked.

Change the method IniciarAnimacoes() to use the object imgPiguim obtained in the onCreate()

private void IniciarAnimacoes() {

    //Animaçoes dos pinguins
    anim = AnimationUtils.loadAnimation(this, R.anim.movimento_pinguim);
    anim.reset();

    //Isto deveria ser passado para o `onCreate()`
    imgPiguim.setBackgroundResource(R.drawable.background_pinguim_anima);

    //Comentei por que não é utilizada
    //animaPiguim = (AnimationDrawable)imgPiguim.getBackground();

    imgPiguim.clearAnimation();
    imgPiguim.startAnimation(anim);
}
  • because then that’s exactly how I’m doing, and the event does not respond in the image that’s in motion

  • You already said that in the question so before answering, I tested the code and it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.