简体   繁体   中英

changing image s for 1 second in android imageview

I am trying to change image after 1 second for image view.but its doesn't show any image on screen. following is code.please help.thank you.

code-

public class Shapes extends Activity {

     Timer timer = new Timer();
     int flag;
     String images[]={};
     ImageView iv;
     static int v[]={R.drawable.round,R.drawable.rectangle};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shapes);
         iv=(ImageView) findViewById(R.id.imageView1);

         timer.schedule(new TimerTask() {

             public void run() {
                 runOnUiThread(new Runnable() {

                     public void run() {

                        if (flag > 1) {
                             timer.cancel();
                             timer = null;
                         } else
                             iv.setImageResource(v[flag++]);

                     }
                 });

             }
         }, System.currentTimeMillis(), 1000);

    }
}

how can i check resource image and change it

Use Handler instead of Timer

Handler handler = new Handler();

Runnable changeImage = new Runnable(){

    @Override
    public void run(){
        if(flag>1)
           handler.removeCallbacks(changeImage);
        else{
           iv.setImageResource(v[flag++]);
           handler.postDelayed(changeImage, 1000);
        }
    }

};

start the first time from oncreate()

public void onCreate(Bundle b){

    handler.postDelayed(changeImage, 1000);
}
timer.scheduleAtFixedRate(new TimerTask() {

     public void run() {
             runOnUiThread(new Runnable() {

                 public void run() {
                     flag++;
                      if (flag > 1) {
                          timer.cancel();
                          timer = null;
                      } 
                      else
                          iv.setImageResource(v[flag]);
                     }
                 });

             }
         }, 1000, 1000); // wait 1 second before start.. then repeat every second..

It's because you put System.currentTimeMillis() as delay. Try replacing that with 0, because the time should start after 0 ms.

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