Nidhin Velayudhan Nidhin Velayudhan - 1 month ago 8
Android Question

How to animate an ImageButton randomly in Android

I want to make a game like kill the bugs, in which the bug will move in a random order. But, when the user touches it, the image changes to a squished bug.

How can I animate a random movement for an

ImageButton
in Android?

Answer

You could use ViewPropertyAnimator, here's a quick example:

activity_main.xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@android:drawable/ic_dialog_info"/>
</RelativeLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity implements Animator
    .AnimatorListener {

    Random random = new Random();
    ImageButton imageButton;
    int maxX;
    int maxY;

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

        imageButton = (ImageButton) findViewById(R.id.imageButton1);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // stopping the animation and changing the image
                imageButton.animate().cancel();
                imageButton.setImageResource(android.R.drawable.ic_delete);
            }
        });

        imageButton.post(new Runnable() {
            @Override
            public void run() {
                maxX = imageButton.getRootView()
                    .getRight() - imageButton.getWidth();
                maxY = imageButton.getRootView()
                    .getBottom() - imageButton.getHeight();

                animateButton();
            }
        });
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        animateButton();
    }

    private void animateButton() {
        imageButton.animate()
            .x(random.nextInt(maxX))
            .y(random.nextInt(maxY))
            .setDuration(1000)
            .setListener(this);
    }

    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationCancel(Animator animation) {
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
    }
}