我在android編程中很新穎,我正在嘗試做一個簡單的遊戲。我想要有3個方格,並且在開始按鈕上我想生成一些隨機數並旋轉其中一個正方形。我在循環中這樣做,因爲我的隨機數的數量不固定。android studio中的循序動畫,循環
package com.example.smartpc.memorygame;
import android.graphics.drawable.TransitionDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MemoryGame extends AppCompatActivity {
ImageView imgRed;
ImageView imgGreen;
ImageView imgBlue;
Button btnStart;
ArrayList<Integer>array=new ArrayList<>();
int brojac=3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory_game);
imgRed=(ImageView)findViewById(R.id.imgRed);
imgGreen=(ImageView)findViewById(R.id.imgGreen);
imgBlue=(ImageView)findViewById(R.id.imgBlue);
btnStart=(Button)findViewById(R.id.btnStart);
final RotateAnimation animation=new RotateAnimation(0f,360f, RotateAnimation.RELATIVE_TO_SELF,0.5f,
RotateAnimation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(1000);
imgRed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgRed.startAnimation(animation);
}
});
imgGreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgGreen.startAnimation(animation);
}
});
imgBlue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgBlue.startAnimation(animation);
}
});
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<brojac;i++) {
Random rand = new Random();
int number = rand.nextInt() % 3;
if (number == 1) {
imgRed.startAnimation(animation);
}
else if (number == 2) {
imgGreen.startAnimation(animation);
}
else {
imgBlue.startAnimation(animation);
}
}
}
});
}
}
我需要等到一個動畫完成,然後我需要啓動另一個循環迭代。有沒有人有想法如何做到這一點?謝謝!
也許並不理想,但是你知道你的'動畫'會持續一秒'animation.setDuration(1000);'你可以在循環的每次迭代結束時進行睡眠嗎? –
我試過了,但如果我有3次迭代,系統會休眠3秒,然後開始動畫。它不會執行動畫代碼,然後進入睡眠狀態,但是在整個循環之後會啓動動畫。 –