Reputation: 717
i have an image view & an array that contain image URLs .I have to traverse through array & set image in image view after every 3 sec...say at start image in image view whose url is at index zero of array then after 3 sec image view should display image at index 1 of array and so on.Please help
Upvotes: 1
Views: 2670
Reputation: 6707
Use this to update your imageview periodically...
Timer timer = null;
int i = 0;
imgView=(ImageView)findViewById(R.id.img);
timer = new Timer("TweetCollectorTimer");
timer.schedule(updateTask, 6000L, 3000L);//here 6000L is starting //delay and 3000L is periodic delay after starting delay
private TimerTask updateTask = new TimerTask() {
@Override
public void run() {
YourActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() { // TODO Auto-generated method stub
imgView.setImageResource(photoAry[i]);
i++;
if (i > 5)
{
i = 0;
}
}
});
}
};
int photoAry[] = { R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
R.drawable.photo4, R.drawable.photo5, R.drawable.photo6 };
for stoping this you can call
timer.cancel();
Upvotes: 1
Reputation: 3080
you can use Timer of specific time period that will repeat the function after time interval.
you can use some code like this:
ImageView img = (ImageView)findViewById(R.id.imageView1);
int delay = 0; // delay for 0 milliseconds.
int period = 25000; // repeat every 25 seconds.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SampleTimerTask(), delay, period);
public class SampleTimerTask extends TimerTask {
@Override
public void run() {
//MAKE YOUR LOGIC TO SET IMAGE TO IMAGEVIEW
img.setImageResource(R.drawable.ANYRANDOM);
}
}
Hope it will work for you.
Upvotes: 0
Reputation: 34360
You should use Handler's postDelayed
function for this purpose. It will run your code with specified delay on the main UI thread
, so you will be able to update UI controls
.
private int mInterval = 3000; // 3 seconds by default, can be changed later
private Handler mHandler;
@Override
protected void onCreate(Bundle bundle) {
...
mHandler = new Handler();
}
Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
updateYourImageView(); //do whatever you want to do in this fuction.
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
Upvotes: 0
Reputation: 7110
try using a handler and set the image to the imageView in the handler code.
Upvotes: 0