问题描述
我设置了事件监听器,例如:setOnClickListener
像这样
I set up event listener, for example: setOnClickListener
like this
Button stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doMagic();
}
});
如果未按下按钮,我想将此侦听器设置为 10 秒的超时事件.用例:我有 button1
激活这个 stopBtn
监听器 10 秒,如果超时,它会被停用,我需要按 button1
使 stopBtn
再次激活.
I would like to set this listener a timeout event on 10s if button is not pressed. Use case: i have button1
that activates this stopBtn
listener for 10s and if timeout comes it becomes deactivated and i need to press button1
to make stopBtn
active again.
我可能做错了:
final Handler myHandler = new Handler();
startBtn = (Button)findViewById(R.id.start);
myHandler.postDelayed(new Runnable() {
public void run() {
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"runned");
}
});
}
}, 10000);
10 秒后,我仍然可以单击它,这可能是 cos 事件侦听器仍然附加.即使我不知道它是否被解雇,我该如何分离它.
After 10s im still able to click it and that is probably cos event listener is still attached. How can i detach it even if i don't know if its fired or not.
推荐答案
A delayed Runnable 发布在处理程序上可以管理:
A delayed Runnable posted on a Handler could manage that:
myHandler.postDelayed(new Runnable() {
public void run() {
if(something happened) {
// magic work
} else {
// turn off the event
}
}
, 10000);
您可以使用这个将 Handler 初始化为实例变量代码:
You can init the Handler as an instance variable by using this code:
final Handler myHandler = new Handler();
这篇关于Android 中事件侦听器的超时检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!