我试图在我的一个活动的onCreate()方法期间显示进度对话框,完成工作以填充线程中完成的屏幕,然后关闭进度对话框.
这是我的onCreateMethod()
dialog = new ProgressDialog(HeadlineBoard.this);
dialog.setMessage("Populating Headlines.....");
dialog.show();
populateTable();
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
Cru*_*ceo 28
如果您已经拥有"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");
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
这应该适合你
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) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
而不是创建一个线程,并使用runOnUIThread,这是ASyncTask的完美工作:
在 中onPreExecute,创建并显示对话框。
在doInBackground 准备数据时,但不要触摸 UI - 将每个准备好的数据存储在一个字段中,然后调用publishProgress.
在onProgressUpdate读取数据字段并对 UI 进行适当的更改/添加。
在onPostExecute关闭对话框中。
如果您有其他原因想要一个线程,或者正在向现有线程添加 UI 触摸逻辑,那么执行与我所描述的类似的技术,仅在 UI 线程上运行一小段时间,runOnUIThread用于每个 UI 步骤。在这种情况下,您将每个数据存储在一个局部final变量(或您的类的字段)中,然后在一个runOnUIThread块中使用它。
| 归档时间: |
|
| 查看次数: |
92750 次 |
| 最近记录: |