我想使用for循环,一个String数组和可绘制文件夹中的png图像来更改图像视图的图像。一个图像应该休息5秒然后下一个应该出现。这是我使用的代码。并且它没有正常工作。图像没有变化。每个循环等待5秒,但图像没有变化。最后一张图像被加载。请有人帮助我......
private String [] array1 = {"card2c","card2d","card2h","card2s",
"card3c","card3d","card3h","card3s",
"card4c","card4d","card4h","card4s",
"card5c","card5d","card5h","card5s",
"card6c","card6d","card6h","card6s",
"card7c","card7d","card7h","card7s",
"card8c","card8d","card8h","card8s",
"card9c","card9d","card9h","card9s",
"card10c","card10d","card10h","card10s",
"cardjc","cardjd","cardjh","cardjs",
"cardqc","cardqd","cardqh","cardqs",
"cardkc","cardkd","cardkh","cardks",
"cardac","cardad","cardah","cardas",};
for(int j=0;j<52;j++)
{
int resID_temp1 = getResources().getIdentifier(array1[j] , "drawable", getPackageName());
Drawable image_temp1 = getResources().getDrawable(resID_temp1);
Player1.setImageDrawable(image_temp1); // Player1 is the ImageView
try {
Thread.sleep(5000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
尝试了计时器
(for(int j=0;j<52;j++)
{
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//switch image here
int resID_temp1 = getResources().getIdentifier(array1[j] , "drawable", getPackageName());
Drawable image_temp1 = getResources().getDrawable(resID_temp1);
Player1.setImageDrawable(image_temp1);
}
}, 0, 5000);
答案 0 :(得分:0)
尝试使用计时器:
//Declare final variable here
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//Switch (declared final) image variable here
}
});
}
}, 0, 5000);
这样的事情......虽然我不在我的电脑旁边。
概念:runOnUithread和final变量也可能有待阅读。 final是因为否则变量不能在另一个线程上操作(实际上它实际上只是另一个范围)。 RunOnUiThread是因为只能在主UI线程上操作图形组件,尽管TimerTask在另一个单独的线程上运行。
答案 1 :(得分:0)
根据您的代码示例,您正在更改图像资源,但随后立即睡眠更改图像资源的相同线程将阻止它并防止图像明显更改(如果这是UI线程,则特别糟糕)这会锁定你的应用程序。)
你应该按照JohnyTex的建议,使用TimerTask每隔5秒更改一次图像,不需要睡眠,因此不会阻止当前线程。