我想在两行代码之间暂停一下,让我解释一下:
->用户点击一个按钮(事实上是一张卡片),我通过改变这个按钮的背景来显示它:
thisbutton.setBackgroundResource(R.drawable.icon);
->让我们说1秒后,我需要通过改变它的背景回到按钮的前一个状态:
thisbutton.setBackgroundResource(R.drawable.defaultcard);
我试着在这两行代码之间暂停线程:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
然而,这是行不通的。也许这是进程,而不是线程,我需要暂停?
我也试过(但没用):
new Reminder(5);
用这个:
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}
}
如何暂停/休眠线程或进程?
你可以试试这件,它很短
SystemClock.sleep(7000);
警告:永远不要在UI线程上这样做。
用这个睡觉。后台线程。
你的问题的完整解决方案是:
这是可用的API 1
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View button) {
button.setBackgroundResource(R.drawable.avatar_dead);
final long changeTime = 1000L;
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.avatar_small);
}
}, changeTime);
}
});
不需要创建tmp处理程序。此外,这个解决方案比@tronman更好,因为我们不通过Handler保留视图。
我们也没有在坏线程创建Handler的问题;)
文档
公共静态空白睡眠(长毫秒)
在API级别1中添加
在返回之前等待给定的毫秒数(uptimeMillis)。类似于sleep(long),但不抛出InterruptedException;Interrupt()事件被延迟到
下一个可中断操作。
至少在经过指定的毫秒数之后才返回。
参数
Ms在返回前进入睡眠状态,正常运行时间以毫秒计。
视图类postDelayed的代码:
/**
* <p>Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* @see #post
* @see #removeCallbacks
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
return true;
}