How to automatically Click a Button in Android after a 5 second delay

前端 未结 3 518
终归单人心
终归单人心 2020-12-04 00:51

I have a small Android application that automatically clicks the button after 5 seconds. I have used performClick(); but this does not work. When the timer gets

3条回答
  •  再見小時候
    2020-12-04 01:20

    You should post your logcat that includes the error message but one issue might be that you are accessing a UI element off the UI thread which isn't a good idea.

    To do what you want you really don't need another thread. You can use a Handler and a delayed Runnable instead like below.

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            button1.performClick();
        }
    }, 5000);
    

    This will schedule the Runnable to be executed on the UI thread after 5 seconds. If that still crashes post the stack trace from logcat.

提交回复
热议问题