在我的一个活动的onCreate()方法期间,我试图显示一个进度对话框,在线程中完成填充屏幕的工作,然后关闭进度对话框。
这是我的onCreateMethod()
dialog = new ProgressDialog(HeadlineBoard.this);
dialog.setMessage("Populating Headlines.....");
dialog.show();
populateTable();populateTable方法包含我的线程和关闭对话框的代码,但由于某种原因。该活动出现大约10秒的空白(执行populateTable()工作),然后我看到了屏幕。我从来没有看到过显示的对话框,有什么想法吗?
下面是populateTable()代码:
//Adds a row to the table for each headline passed in
private void populateTable() {
new Thread() {
@Override
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}发布于 2012-06-29 08:21:00
如果您已经有了数据"for (Parcelable currentHeadline : allHeadlines)“,那么为什么还要在一个单独的线程中这样做呢?
您应该在一个单独的线程中轮询数据,当它完成收集数据时,然后在UI线程上调用populateTables方法:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}发布于 2012-06-29 08:27:18
这对你来说应该是可行的
public class MyActivity extends Activity {
protected ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateTable();
}
private void populateTable() {
mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
new Thread() {
@Override
public void run() {
doLongOperation();
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}
/** fake operation for testing purpose */
protected void doLongOperation() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
}
}发布于 2014-11-08 01:20:34
对于ASyncTask来说,这是一项完美的工作,而不是创建线程并使用runOnUIThread
在
doInBackground 中的
publishProgress.
onProgressUpdate读取数据字段并对UI进行适当的更改/添加。<代码>H214<代码>H115关闭对话框。<代码>H217<代码>F218如果您有其他需要线程的原因,或者正在向现有线程添加与UI相关的逻辑,那么可以使用类似于我所描述的技术,只在UI线程上运行一小段时间,对每个UI步骤使用runOnUIThread。在这种情况下,您将把每个数据存储在一个本地final变量中(或您的类的一个字段中),然后在runOnUIThread块中使用它。
https://stackoverflow.com/questions/11254523
复制相似问题