我需要设置setImageResource,暂停并更改为不同的setImageResource

时间:2015-02-15 21:25:51

标签: java android image

我试图设置一个图像并在一个小暂停(如闪烁)后将其更改为不同的图像; 它应该在应用程序启动后自动启动。

public class MainActivity extends ActionBarActivity {

ImageView image1;

private void flash(){
    Thread flashing=new Thread(){
        public void run(){
            try {
                image1.setImageResource(R.drawable.red_circle);
                sleep(1000);
                image1.setImageResource(R.drawable.white_circle);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    flashing.start();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    image1=(ImageView)findViewById(R.id.imageView1);

    flash();

}

} 这会导致错误和应用程序停止。

1 个答案:

答案 0 :(得分:1)

试试这个:

ImageView slide;
private Handler handler;
private int showPic = -1;// default value should be -1
Integer[] ids = new Integer[] { R.drawable.red_circle, R.drawable.white_circle};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.slide_show);
    slide = (ImageView) findViewById(R.id.slide);
    handler = new Handler();
    handler.postDelayed(imageUpdate, 10);
}


private void setNextImage() {
    showPic++;
    if (showPic == ids.length) {
        showPic = -1;
        handler.removeCallbacks(imageUpdate);
    } else {
        slide.setImageResource(ids[showPic]);
        handler.postDelayed(imageUpdate, 1000);
    }
}

Runnable imageUpdate= new Runnable() {
    @Override
    public void run() {
        setNextImage();
    }
};  

更新:如果您想在图片上循环,可以将setNextImage()方法更改为此,还要注意我将showPic的默认值更改为-1(如果您想要循环或不其默认值应为-1):

private void setNextImage() {
    showPic++;
    if (showPic == ids.length) {
        showPic = 0;
    }
    slide.setImageResource(ids[showPic]);
    handler.postDelayed(imageUpdate, 1000);
}  

onDestroy()方法中删除callBack:

public void onDestroy(){
     handler.removeCallback(imageUpdate);
     super.onDestroy();
}