我想制作一个类似于杀死bug的游戏,其中bug将以随机顺序移动。但是,当用户触摸它时,图像会变成一个压扁的bug。
如何为Android中的ImageButton
设置随机动画?
答案 0 :(得分: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) {
}
}