How to set delay in Android onClick function

心不动则不痛 提交于 2019-11-27 01:58:08
Ryan Reeves

Instead of sleeping in the onclick, you could post a delayed message to a handler (with associated runnable) and have it update the UI. Obviously fit this into the design of your app and make it work, but the basic idea is this:

//Here's a runnable/handler combo
private Runnable mMyRunnable = new Runnable()
{
    @Override
    public void run()
    {
       //Change state here
    }
 };

Then from onClick you post a delayed message to a handler, specifying that runnable to be executed.

Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 1000);//Message will be delivered in 1 second.

Depending on how complicated your game is, this might not be exactly what you want, but it should give you a start.

Ali Mohammadi

Correctly work:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 100ms
  }
}, 100);

You never should sleep in UI thread (by default all your code runs in UI thread) - it will only make UI freeze, not let something change or finish. I can't suggest more because I don't understand code logic.

Do not sleep in the UI thread. You need another thread that will look for a "wake up and wait" message from your UI thread. That second thread could then do your hiding after a normal sleep call. You could then keep the thread around for the next time you need to hide something, or kill it and whip up a new one each time you need another delay.

I believe there are some "postFoo" functions that might be useful in this context (triggering UI events from outside the UI thread).

Anand Mohan
b.setOnClickListener(new OnClickListener() {

    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        final ProgressDialog myPd_ring=ProgressDialog.show(MainActivity.this, "confident checker", "calculating please wait..", true);
        myPd_ring.setCancelable(true);
        new Thread(new Runnable() {  
              public void run() {
                    // TODO Auto-generated method stub


                    try
                    {
                          Thread.sleep(5000);


                    }
                    catch(Exception e){}
                    b.dismiss();
              }
        }).start();


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          public void run() {
              Toast.makeText(getApplicationContext(), "today your confident level is 90% ",
                        Toast.LENGTH_LONG).show();

          }
        }, 5000);


    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!