Android - display series of images using ImageView
I try to display series of png images in a single ImageView using Timer (e.g. change pic every 1 sec.).
The app keep crashing, Here is my code, please help. There is ImageView in the main.xml , for some reason i cant post the full xml file here. Anyway it just a standard main.xml with extra ImageView within the Linear Layout.
public class AniImgTest extends Activity {
ImageView iv;
public int i=0;
开发者_运维问答 Timer timer = new Timer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.iv=(ImageView)findViewById(R.id.imageView1);
timer.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
Log.v("","myDebug "+i);
if(i<2)
i++;
else
i=0;
switch(i){
case 0:iv.setImageResource(R.drawable.a1);
break;
case 1:iv.setImageResource(R.drawable.a2);
break;
case 2:iv.setImageResource(R.drawable.a3);
break;
}
}
}, 0, 5000);
}
}
Your task is running on a different thread than main thread, so it can't change the GUI and causes crashes. Use handler to perform those tasks on the main thread.
One more thing (which is not related, but...), instead of:
if(i<2)
i++;
else
i=0;
switch(i){
you can write:
switch(++i % 3){
use this block of code to change UI components
AniImgTest.this.runOnUiThread(new Runnable() {
public void run() {
// change your image here.
}
});
精彩评论