使用定时器设置图像
我正在尝试使用倒计时器设置延迟 600 毫秒的图像,如下所示:
protected void onCreate(Bundle savedInstanceState) {
int order[3];
index=0;
image1.setOnClickListener(this);
@Override
public void onClick(View arg0)
{
order={2,1,3};
do_switches();
}
private void do_switches()
{
new CountdownTimer(3*600, 600) {
public void onTick(long millisUntilFinished) {
switch(order[index]){
case 1:
image1.setImageResource(R.drawable.one);
break;
case 2:
image2.setImageResource(R.drawable.two);
break;
case 3:
image3.setImageResource(R.drawable.three);
break;
}
index++;
}
public void onFinish() {
}
}.start();
}
}
这是一个示例,但在我的实际代码中,我使用更大的数组(大小约为 50)。我的问题是,倒计时器并不总是一直到数组中的最后一个位置。有时有效,但有时它会在到达数组的最后一点之前停止。但是,如果我将间隔时间增加到 2000 毫秒,它总是有效。这肯定是一些处理过程延迟了这一点,但我不认为倒计时不会因为我缩短了间隔而不起作用。有人可以告诉我可以做什么来确保倒计时器在遍历整个数组之前不会停止,或者是否有更好的方法来做到这一点。
我还尝试使用带有 ScheduleAtFixedRate 的计时器,但出现错误,提示我无法触摸线程中的视图,因为它们不是在线程中构造的
请帮助 谢谢
I am trying to set images with a 600ms delay using a countdown timer as follows:
protected void onCreate(Bundle savedInstanceState) {
int order[3];
index=0;
image1.setOnClickListener(this);
@Override
public void onClick(View arg0)
{
order={2,1,3};
do_switches();
}
private void do_switches()
{
new CountdownTimer(3*600, 600) {
public void onTick(long millisUntilFinished) {
switch(order[index]){
case 1:
image1.setImageResource(R.drawable.one);
break;
case 2:
image2.setImageResource(R.drawable.two);
break;
case 3:
image3.setImageResource(R.drawable.three);
break;
}
index++;
}
public void onFinish() {
}
}.start();
}
}
This is an example but in my actual code, I use larger arrays (about 50 in size). My problem is, the countdown timer does not always go all the way to the last spot in the array. Sometimes works but other times it stops before reaching the last point of my array. However if I increase the interval time to be 2000ms it always works. Its definitely some processing going on that delays this but I don't expect a countdown to not work just because I have reduced the interval. Can someone tell me what I can do to make sure the countdown timer does not stop before going through my whole array or is there a better way to do this.
I also tried using a timer with scheduleAtFixedRate but I got an error saying I cannot touch views in a thread because they were not constructed in the thread
Please help
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我确信还涉及其他细节,这可能无法解决所有问题,但对于最后一点(“...无法触摸线程中的视图...”),您需要将 Runnable 传递给 Activity.runOnUiThread。在该 Runnable 中,设置图像资源以及任何其他会影响屏幕的内容。
I'm sure there are other details involved and this may not cure everything, but for the last bit ("...cannot touch views in a thread..."), you need to pass a Runnable to Activity.runOnUiThread. In that Runnable, do your setting of image resources and anything else that will affect the screen.