如果按钮空闲,如何启动线程?

我需要一个线程在按钮空闲 3 秒后启动,有没有一种简单的方法可以做到这一点?

我正在构建一个计数器应用程序,按钮触发两个计数器,总计数器和“点击计数器”,点击计数器有助于跟踪值的实际变化,显示用户点击了多少次,我需要它消失几秒钟后,用户可以再次点击。


DIEA
浏览 89回答 3
3回答

一只甜甜圈

对于这样的事情,我通常使用带有Runnable 的处理程序,以便在 X用户未执行特定操作后执行操作。milliseconds首先,创建一个runnable和一个handlerfinal 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@Overridepublic 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);       }    });}我希望这会有所帮助,如有任何问题,请随时提出

慕盖茨4494581

Handler 可能会在这种场景下工作,有 3000 毫秒的延迟。new Handler().postDelayed(new Runnable() {        @Override        public void run() {          // do action        }    }, 3000);

30秒到达战场

首先,您创建一个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);    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java