我是Android的新手,我正在尝试在android studio中制作一个图像按钮来改变设置inervals的图像。我试图使用wait并将其放入不同的线程,但这似乎不起作用。我想要的只是为了改变图像,同时还允许在这样的情况下播放mp3。
Runnable r = new Runnable() {
@Override
public void run()
{
synchronized (this)
{
try
{
wait(1000);
ank.setImageResource(R.drawable.shank2);
wait(1000);
ank.setImageResource(R.drawable.shank3);
wait(1000);
ank.setImageResource(R.drawable.shank4);
wait(1000);
ank.setImageResource(R.drawable.shank5);
}
catch (Exception e) {}
}
}
};
Thread myThread = new Thread(r);
myThread.start();
答案 0 :(得分:0)
简单方法:
public void changeImages() {
Handler uiHandler = new Handler();
uiHandler.postDelayed(new Runnable {
@Override
public void run() {
ank.setImageResource(R.drawable.shank1);
}
}, 1000);
uiHandler.postDelayed(new Runnable {
@Override
public void run() {
ank.setImageResource(R.drawable.shank2);
}
}, 2000);
...
}
更好的方式:
public void changeImages() {
int[] images = new int[] { R.drawable.shank1, R.drawable.shank2 ... }
long delay = 1000;
Handler uiHandler = new Handler();
for (int imageRes : images) {
uiHandler.postDelayed(new Runnable {
@Override
public void run() {
ank.setImageResource(imageRes);
}
}, delay);
delay += 1000;
}
}
最好的方式
final Handler uiHandler = new Handler();
final Queue<Integer> queue = new LinkedBlockingQueue<>();
void changeImages() {
queue.add(R.drawable.shank1);
queue.add(R.drawable.shank2);
...
loopImages();
}
void loopImages() {
if (!queue.isEmpty()) {
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
ank.setImageResource(queue.poll());
}
}, 1000);
}
}