[英]How to make an image change when clicking on a button
I am displaying image on when clicking on a Button
using interface but the image ic_launcher.png
does not show up on the Button
after some time the image_all.png
is only shown. 我在使用界面单击Button
时显示图像,但是一段时间后,仅显示image_all.png
图像ic_launcher.png
并没有显示在Button
上。
Any help would be appreciated. 任何帮助,将不胜感激。
try{
button1.setBackgroundResource(R.drawable.ic_launcher);
Thread.sleep(1000);
} catch(Exception e){
}
button1.setBackgroundResource(R.drawable.images_all);
When you use Thread.sleep(1000);
当您使用Thread.sleep(1000);
you're actually "stopping" the UI thread, because you're calling sleep(1000);
您实际上是在“停止” UI线程,因为您正在调用sleep(1000);
on the UI thread. 在UI线程上。 This causes your application to halt completely for 1 second in your case. 在这种情况下,您的应用程序将完全停止1秒钟。
So this isn't such a good idea :-) 所以这不是一个好主意:-)
Instead you should use something like a Handler
for instance. 相反,您应该使用诸如Handler
类的东西。 A Handler
can be called with a specified delay, so that the action will first be performed after the specified delay. 可以在指定的延迟后调用Handler
,以便在指定的延迟后首先执行操作。 And most importantly, the Handler
doesn't "block" the UI thread, as the Thread.sleep(1000);
最重要的是, Handler
不会“阻塞” UI线程,就像Thread.sleep(1000);
does. 做。
So using a Handler
your code, could look something like this instead: 因此,使用Handler
您的代码,可能看起来像这样:
button1.setBackgroundResource(R.drawable.ic_launcher);
Handler uiHandler = new Handler();
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
button1.setBackgroundResource(R.drawable.images_all);
}
}, 1000);
Notice the 1000
in the end of postDelayed()
which tells the Handler
to post this "message" after 1000 milliseconds instead of immediately. 注意postDelayed()
末尾的1000
,它告诉Handler
在1000毫秒后而不是立即发布此“消息”。
On a side-note: It's not good practice to "eat" the Exceptions
like you do in your try-catch
. 附带说明:像在try-catch
那样“吃掉” Exceptions
不是一个好习惯。
You should be able to see the R.drawable.ic_launcher
change occur. 您应该能够看到R.drawable.ic_launcher
发生了变化。 My thoughts about this are around how you're doing the Thread.sleep()
. 我对此的想法是关于您如何执行Thread.sleep()
。 Android isn't fond of performing blocking tasks (such as Thread.sleep) in the UI Thread. Android不喜欢在UI线程中执行阻止任务(例如Thread.sleep)。 When you call the setBackgroundResource and then sleep, the thread that would update the UI is sleeping and cannot perform the update. 当您调用setBackgroundResource然后进入睡眠状态时,将更新UI的线程处于睡眠状态,无法执行更新。 This is how I would do it instead: 这就是我要做的:
button1.setBackgroundResource(R.drawable.ic_launcher);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
button1.setBackgroundResource(R.drawable.images_all);
}
}, 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.