我想知道我的代码吼叫,我找不到错误点。任何人都可以解释一下,错误点是什么?
我想点击按钮并延迟3秒然后将出现Toast。
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
int timeout = 10000;
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
@Override
public void run()
{
finish();
Toast.makeText(TestActivity.this, "Timer is work", Toast.LENGTH_SHORT).show();
}
}, timeout);
}
});
答案 0 :(得分:1)
使用Handler
。 Timer在不同的线程上运行。你应该在ui线程上更新ui。使用runOnUiThread
I want to click on button and delay 3s then will Toast will appear.
使用以下
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// do something
}
}, 3000);
public final boolean postDelayed (Runnable r, long delayMillis)
Added in API level 1
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
Parameters
r The Runnable that will be executed.
delayMillis The delay (in milliseconds) until the Runnable will be executed.
Returns
Returns 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.
如果你想每3秒重复一次吐司
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
@Override
public void run() {
Toast.makeText(TestActivity.this, "Timer is work", Toast.LENGTH_SHORT).show();
m_handler.postDelayed(m_handlerTask, 3000);
}
};
m_handlerTask.run();
要取消运行,请使用m_handler.removeCallbacks(m_handlerTask);
使用Timer
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
//update ui
}
});
}
}, 1000, 1000 ); // change to 3000
答案 1 :(得分:1)
Timer
在另一个线程中运行,你不能在另一个线程中显示Toast
..所以在UI线程中显示Toast ..
你为什么要在展示吐司之前完成你的活动..
像这样改变你的代码..
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int timeout = 10000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,
"Timer is work", Toast.LENGTH_SHORT)
.show();
finish();
}
});
}
}, timeout);
}
});
答案 2 :(得分:1)
这很简单
修改您的代码如下: -
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
int timeout = 10000;
Timer timer = new Timer();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
ACTIVITY_NAME.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "Timer is work",Toast.LENGTH_SHORT).show(); }
});
}
}, timeout);
});