【问题标题】:How to animate an ImageButton randomly in Android如何在 Android 中随机为 ImageButton 设置动画
【发布时间】:2016-11-03 11:08:57
【问题描述】:

我想做一个游戏,比如杀死虫子,其中虫子会以随机顺序移动。但是,当用户触摸它时,图像会变成一个被压扁的虫子。

如何在 Android 中为ImageButton 制作随机移动动画?

【问题讨论】:

  • 显示输出截图
  • 在下面用一个例子更新了我的答案

标签: android image button


【解决方案1】:

您可以使用ViewPropertyAnimator,这是一个简单的示例:

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) {
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多