why ImageView can#39;t update before SystemClock.sleep()(为什么 ImageView 在 SystemClock.sleep() 之前无法更新)
问题描述
我想在翻转旧图像之后的 3 秒内在 ImageView 中显示其他图像.代码:
I want to show other image in ImageView within 3 second, after that rollover old image. The code:
OnClickListener oc = new OnClickListener() {
@Override
public void onClick(View v) {
ImageView iv = (ImageView)v;
iv.setImageResource(img2_id);
SystemClock.sleep(3000);
iv.setImageResource(img1_id);
}
}
myImageView.setOnClickListener(oc);
但它不起作用?那么,我是不是做错了什么?
But it doesn't work? So, am I doing something wrong?
推荐答案
你阻塞了 UI 线程.因此在睡眠命令期间,屏幕不会刷新.您需要安排对更改图像资源的函数的非阻塞延迟调用.这是一个修改后的代码,可以做这样的事情:
You are blocking the UI thread. Thus during the sleep command, the screen won't refresh. What you need is to schedule a non-blocking delayed call to a function which changes image resource. Here is a modified code that would do such a thing:
Handler mHandler = new Handler(); /*handler declared in your Activity thread, I assume*/
OnClickListener oc = new OnClickListener() {
@Override
public void onClick(View v) {
ImageView iv = (ImageView)v;
iv.setImageResource(img2_id);
mHandler.postDelayed(new Runnable(){
public void Run(){
iv.setImageResource(img1_id);
}
},3000);
}
}
myImageView.setOnClickListener(oc);
这篇关于为什么 ImageView 在 SystemClock.sleep() 之前无法更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!