3 回答
TA贡献1836条经验 获得超5个赞
对于这样的事情,我通常使用带有Runnable 的处理程序,以便在 X用户未执行特定操作后执行操作。milliseconds
首先,创建一个runnable
和一个handler
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
然后添加onClickListener:
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
然后,在onClick事件内部,删除callbacks并重新实例化,handler如下所示:
if(runnable != null) {
// in this case the user already clicked once at least
handler.removeCallbacks(runnable);
}
runnable = new Runnable() {
@Override
public void run() {
//this code will run when user isn't clicking for the time you set before.
}
};
handler.postDelayed(runnable, DELAY);
最后结果:
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// all your previous stuffs
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(runnable != null) {
// in this case the user already clicked once at least
handler.removeCallbacks(runnable);
}
runnable = new Runnable() {
@Override
public void run() {
//this code will run when user isn't clicking for the time you set before.
}
};
handler.postDelayed(runnable, DELAY);
}
});
}
我希望这会有所帮助,如有任何问题,请随时提出
TA贡献1850条经验 获得超11个赞
Handler 可能会在这种场景下工作,有 3000 毫秒的延迟。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// do action
}
}, 3000);
TA贡献1828条经验 获得超6个赞
首先,您创建一个Timerwith a TimerTask(使用您的线程)并安排它在 3 秒后运行。
每次按下按钮,您都会重置计时器。
public class MyClass{
private Timer timer=new Timer()
private TimerTask task=new TimerTask(){
public void run(){
//your action
}
};
public void init(){
timer.schedule(task,3000);
}
public void onButtonClick(){
task.cancel();
timer.schedule(task,3000);
}
}
添加回答
举报