How to automatically Click a Button in Android after a 5 second delay如何在Android的自動點擊一個按鈕,每一秒
我與在鏈接進入,但我的應用程序崩潰 我的代碼的代碼嘗試;
public class MainActivity extends AppCompatActivity {
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
Thread timer = new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
button.performClick();
}
}
};
timer.start();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
button.performClick();
}
}, 1000);
}
public void buttonClick() {
button=(Button) findViewById(R.id.button);
text=(TextView) findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random s=new Random();
int number=s.nextInt(3);
switch (number)
{case 1:text.setText("1");
break;
case 2: text.setText("2");
break;
}
}
});
}
}
你不需要點擊一個按鈕的方法,你只需要調用的方法每5秒...... –
和錯誤是因爲你不能像從另一個線程處理GUI元素那 –