问题描述
我有一个自定义对话框,其中包含许多要加载的元素。当提示您在首次加载时显示时,加载需要2-3秒。以后每次加载时,它几乎都是瞬时的。我想第一次去显示对话框时要承受瞬时负载。
通过有限的研究,我觉得利用AsyncTask是合适的方法(通过预加载)。尽管我不确定如何实现这一点。我的想法是预加载对话框,是使用后台线程加载该对话框,然后立即hide()
对话框。然后onClick
,它将show()
对话框。我已完成以下操作:
我全局声明:Dialog dialogFake;
在onCreate
下,我调用方法startAsyncTask();
然后在我的onClick
按钮之一上,我dialogFake.show();
我在MainActivity.class的末尾添加了以下代码
public void startAsyncTask() {
MainActivity.MyAsyncTask task = new MainActivity.MyAsyncTask(this);
task.execute();
}
private class MyAsyncTask extends AsyncTask<Integer,Integer,String> {
MyAsyncTask(MainActivity activity) {
}
@Override
protected String doInBackground(Integer... integers) {
dialogFake.hide();
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialogFake.hide();
}
@Override
protected void onPreExecute() {
dialogFake = new Dialog(MainActivity.this);
dialogFake.setContentView(R.layout.list);
dialogFake.setTitle("Title...");
dialogFake.setCanceledOnTouchOutside(false);
dialogFake.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
ImageView dialogPicture1 = (ImageView) dialogFake.findViewById(R.id.Picture1);
TextView dialogTextLabel1 = (TextView) dialogFake.findViewById(R.id.Label1);
//^More of these... removed for readability
dialogFake.hide();
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialogFake.hide();
}
对话框显示出来,尽管性能没有改变……我还没有为对话框上的每个元素指定特定的值,尽管由于加载的元素数量巨大,性能已经很糟糕了。
编辑
帮助我理解,也许我正在以错误的方式进行尝试或试图完成不可能的事情。 doInBackground()
是AsyncTask中唯一从UI线程分流处理的方法,从而减轻了挂起时间,对吗?
此外,doInBackground()
方法不能处理GUI元素,因为它们是由UI线程处理的,对吗?
因此,在不使用AsyncTask的情况下,我加载的自定义对话框没有任何特定值,仅是customlayout xml文件中指定的默认值(宽度,高度,边距等)。我将对话框和元素加载到onCreate()
中,然后最后hide()
对话框。我通过按钮show()
onClick()
。我不明白的是2-3的加载延迟仍然存在。我只能假设,由于dialogFake.show()
方法是单击按钮时唯一被调用的方法,因此延迟是从将对话框呈现到屏幕上开始的……因此AsyncTask可以“提供”某些东西,以便当{ {1}}叫它准备好了吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)