简体   繁体   中英

I would need to Set setImageResource, pause and change to different setImageResource

I am trying to set a image and change it to different image after a small pause (like a flashing); And it should start automatically after app is started.

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();

}

} This causes error and app to stop.

try this one:

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();
    }
};  

UPDATE: if you want loop on your images you can change setNextImage() method to this, also note that I change default value for showPic to -1(if you want loop or not its default value should be -1):

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

in onDestroy() method remove callBack:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM