random frame animation does not work android
I am trying to achieve a random animation of from a set of images, where each frame is a random image from the image set. And for this I am using addFrame method of AnimationDrawable object but the animation is not working. I tried searching various tutorials, tried other things also but nothing helped. Below is my code of the program, can anyone please tell what I am doing wrong. In the layout there is an ImageView. But when I am trying animation from xml animation definition(which is not random), it works. Thanks and regards.
import java.util.Random;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MemoryGame extends Activity implements OnTouchListener{
MemoryGameView mgv;
ImageView memImg;
int []seqimg = new int[15];
AnimationDrawable a开发者_运维知识库nimation;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.memorylayout);
memImg = (ImageView) findViewById(R.id.mem_img);
memImg.setOnTouchListener(this);
//generate the random sequence of list
randomImgList();
defAnimation();
}
//select the array of random sequence of images for viewing
private void randomImgList(){
//initialize the sequece
for (int i = 0; i < 15; i++) {
seqimg[i] = i+1;
}
Random rng = new Random();
// i is the number of items remaining to be shuffled.
for (int i = 15; i > 1; i--) {
// Pick a random element to swap with the i-th element.
int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array)
// Swap array elements.
int tmp = seqimg[j];
seqimg[j] = seqimg[i-1];
seqimg[i-1] = tmp;
}
}
//define the animation sequece
private void defAnimation() {
animation = new AnimationDrawable();
for(int i=0; i<10; i++) {
String imgName = "mimg" + seqimg[i];
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
Log.d("id",""+id);
animation.addFrame(getResources().getDrawable(id), 1000);
}
animation.setOneShot(true);
}
//define the touch event from the OnTouchListener interface
public boolean onTouch(View v, MotionEvent arg1) {
if(v.getId() == memImg.getId()) {
memImg.setBackgroundDrawable(animation);
animation.setVisible(true, true);
animation.stop();
animation.start();
}
return true;
}
}
I found the problem, I am posting the solution maybe if other find this problem it will be helpful. Actually the animation is working but the initial image which is used to initialize the ImageView is above the animation so the animation was invisible. Now I set the ImageView to a blank image before starting the animation and the animation is visible now. Thanks.
精彩评论