下面是我刚刚写的一个基本示例:
public class AutoChecker extends Activity {
private CheckBox checkbox1;
private CheckBox checkbox2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkbox1 = (CheckBox) findViewById(R.id.checkbox_1);
checkbox2 = (CheckBox) findViewById(R.id.checkbox_2);
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2);
}
private class CheckerAsync extends AsyncTask<CheckBox, CheckBox, Void>{
private Activity mActivity;
private CheckerAsync(Activity activity) {
mActivity = activity;
}
@Override
protected Void doInBackground(final CheckBox... checkboxes) {
try {
for(int i = 0, j = checkboxes.length; i < j; i++ ){
Thread.sleep(5000);
publishProgress(checkboxes[i]);
}
} catch (InterruptedException e) {}
return null;
}
@Override
public void onProgressUpdate(final CheckBox... checkboxes){
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
checkboxes[0].setChecked(true);
}
});
}
}
}
这是XML布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<CheckBox
android:id="@+id/checkbox_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Checkbox 1"
/>
<CheckBox
android:id="@+id/checkbox_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Checkbox 2"
/>
</LinearLayout>
解释
它使用一个扩展
AsyncTask
它允许您以易于使用/理解的方式使用线程。这个类的执行方式有点简单:
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2);
您可以添加任意多的复选框。例如:
new CheckerAsync(AutoChecker.this).execute(checkbox1, checkbox2, checkbox4, checkbox3);
顺便说一下,我不知道你为什么要这么做。但是,如果是出于测试目的,您最好看一下
instrumentation framework
.