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

前端 未结 3 509
终归单人心
终归单人心 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:10

    Use the runOnUiThread() method. This method run your method of UI thread

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 01:24
    protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.local);
        getActionBar().setIcon(R.drawable.menu_drop);
    
        //buttonClick();
    
        Thread timer = new Thread(){
            public void run(){ 
                try{
                    sleep(5000);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }finally{
                    //button1.performClick();
                    getLocationOnClick();
                }
            }
        };
        timer.start();
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
    

    Change you button click method to like this -

    public void getLocationOnClick(View v) {
         Intent i = new Intent(TestButton2.this, LocationView.class);
         startActivity(i);
        } 
    

    In the xml for your Button add an onClick attribute -

     <Button
            android:id="@+id/btnid"
            android:onClick="getLocationOnClick"
            .... >
    
    0 讨论(0)
提交回复
热议问题