[英]How to add controls to view in a worker thread in Android
我需要在运行时在android应用程序中创建几个UI控件。
为了在创建控件时不冻结UI(并显示“正在加载...”框),我想使用如下工作线程:
private class LoadControls extends AsyncTask<TdcItem, Integer, Integer> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(FormActivity.this);
dialog.setMessage(getString(R.string.loading_message));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected Integer doInBackground(TdcItem... items) {
ScrollView accordion = (ScrollView) findViewById(R.id.accordion);
int count = items.length;
for (int i = 0; i < count; i++) {
Button header = new Button(FormActivity.this);
header.setText(items[i].getName());
if (isCancelled()) break;
}
return count;
}
protected void onPostExecute(Integer result) {
dialog.dismiss();
}
}
此代码是“活动”的一部分,将响应按钮的单击。
问题是编译器说我无法在工作线程中创建按钮。 我该怎么做?
它似乎是您想要做的一个UI东西,因此应该在UI线程上完成...否则,您将不得不创建一个
new Handler()
创建一个新的Runnable并调用该处理程序的postOnUiThread()方法不是非常... usefull我猜
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.