我准备好一个arraylist(字符串),其中包含一些图像的Web链接。现在,我想在一段时间间隔(例如4秒)后使用Glide使用图像链接定期更新imageview。 在使用新图像更新imageview之前,设置暂停时遇到了问题。
我的代码:
//i is the count initially set to 0. StringLink is the arraylist
//StatusImage is the imageview
//first I set the first link from StringLink to StatusImage
Glide.with(ShowStatusPostActivity.this).setDefaultRequestOptions(placeholderRequest).load(StringLink.get(i)).into(StatusImage);
//next I try to set the next links from StringLink to StatusImage
//I try to keep one image for 4 seconds and then change it. Here I use Handler to do so
for(; i< StringLink.size();i++ )
{
try{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
StatusImage.post(new Runnable() {
@Override
public void run() {
Glide.with(ShowStatusPostActivity.this).setDefaultRequestOptions(placeholderRequest).load(StringLink.get(i))
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.into(StatusImage);
}
});
}
}, 4000);
}
catch (Exception e){}
}
但是我在第二个Glide中遇到了ArrayIndexOutofBound的错误。
我不认为在for循环内使用Handler是使周期性成为一个很好的主意,我也尝试了Thread.sleep但它也没有起作用。
在这里我能做些什么吗?
答案 0 :(得分:2)
我希望以下功能会有所帮助。每隔4秒钟将触发一次,并显示吐司消息。您可以调用函数以基于I计数器加载图像。
int i = 0;
int length = 5;
private Handler mHandler;
private Runnable mRunnable;
public void startPeriodicFunciton() {
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
// Do some task on delay
// doTask();
// You can add your fuction to load image here
i++;
if (i == length)
i = 0;
Toast.makeText(MainActivity.this, "value : " + i,
Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 4000);
}
};
mHandler.postDelayed(mRunnable, (4000));
}