0

i have imageview and i have to display different image in that with time interval, but when i change the ImageResource the last image is displayed

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);



    ImageView image = (ImageView) findViewById(R.id.test_image);
    image.setImageResource(R.drawable.test);

  try {
        Thread.sleep(2000) ;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);

}

Kindly Suggest the Right way to do that

Thanks in Advance

user321373
  • 1,061
  • 3
  • 10
  • 11
  • 1
    using Thread.sleep() in the UI thread is really bad... and it's also bad that you never accept answers – Dalmas Feb 03 '11 at 15:31

2 Answers2

0

Perhaps this thread is what you are looking for:

Community
  • 1
  • 1
dave.c
  • 10,910
  • 5
  • 39
  • 62
0

Whenever you want to update the user interface without performing any action or event, handlers should be used.

This is the sample code

Main.java

package com.balaji.handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
public class Main extends Activity  { 

    private ImageView txtStatus;
    int i=0;
    int imgid[]={R.drawable.icon,R.drawable.back,R.drawable.slider,R.drawable.forward};
    private RefreshHandler mRedrawHandler = new RefreshHandler();

    class RefreshHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            Main.this.updateUI();
        }

        public void sleep(long delayMillis) {
            this.removeMessages(0);
            sendMessageDelayed(obtainMessage(0), delayMillis);
        }

    };

    private void updateUI(){
        //int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
        if(i<imgid.length){
        mRedrawHandler.sleep(1000);
        txtStatus.setBackgroundResource(imgid[i]);
        i++;
    }
}

@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main);
    this.txtStatus = (ImageView)this.findViewById(R.id.txtStatus);
    updateUI();
}   
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
<ImageView 
    android:id="@+id/txtStatus" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true">
</ImageView>
</RelativeLayout>
Alpine
  • 3,838
  • 1
  • 25
  • 18
Balaji.K
  • 8,745
  • 5
  • 30
  • 39