我的预期结果是在第一次启动时会显示一个进度对话框来等待后台线程加载内容。工作线程完成工作后,对话框消失。我进行了搜索并得到了这个解决方案如何在 Android 中开始活动之前显示进度对话框?
这是我的完整代码:
private ManagerApplication app;
private ImageAdapter adapter;
private GridView gridview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupView();
}
private void setupView() {
gridview = (GridView) findViewById(R.id.gridview);
app = (ManagerApplication) getApplication();
ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new LoadImageTask(progress, this).execute();
}
private class LoadImageTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
private Context context;
public LoadImageTask(ProgressDialog progress, Context context) {
this.progress = progress;
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress.show();
}
@Override
protected Void doInBackground(Void... params) {
adapter = new ImageAdapter(app.getShoes(), context);
gridview.setAdapter(adapter);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
}
}
但是,我的应用程序崩溃的原因是“只有创建视图层次结构的原始线程才能触摸它的视图”。我想有一些东西阻塞了主 UI 线程,但它仍然很不清楚。那么有人可以指出我的问题吗?谢谢