使用setContentView加载布局时显示ProgressDialog

fra*_*llo 12 multithreading android progressdialog android-asynctask android-activity

这是我的场景:我有一个登录屏幕,可以打开另一个活动.在活动中,我只需:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_details);
}
Run Code Online (Sandbox Code Playgroud)

布局有点沉重,因为它是由一些碎片组成的,并且需要大约1.5秒才能加载.现在,我如何显示一段ProgressDialog时间setContentView完成布局?我已经尝试AsyncTask过将其setContentView放入doInBackground,但当然无法完成,因为UI只能从UI线程更新.所以我需要setContentView在UI线程中调用,但是我必须在哪里显示/关闭ProgressDialog

我感谢您的帮助.

弗拉.

编辑:我跟着@ JohnBoker先前的建议,这是我现在的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_empty_layout);
    new ContentSetterTask().execute("");
}

private class ContentSetterTask extends AsyncTask<String, Void, Void> {

    public ProgressDialog prgDlg;

    @Override
    protected void onPreExecute() {
        android.os.Debug.waitForDebugger();
        prgDlg = ProgressDialog.show(MultiPaneActivity.this, "", "Loading...", true);

    }

@Override
protected Void doInBackground(String... args) {
    android.os.Debug.waitForDebugger();
    ViewGroup rootView = (ViewGroup)findViewById(R.id.emptyLayout);
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View inflated = inflater.inflate(R.layout.activity_details, rootView);
    return null;
}

@Override
protected void onPostExecute(Void arg) {
    android.os.Debug.waitForDebugger();
    if (prgDlg.isShowing())
        prgDlg.dismiss();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

View inflated = inflater.inflate(R.layout.activity_details, rootView);
Run Code Online (Sandbox Code Playgroud)

给我错误:

06-27 16:47:24.010:   
ERROR/AndroidRuntime(8830): Caused by:android.view.ViewRoot$CalledFromWrongThreadException: 
Only the original thread that created a view hierarchy can touch its views.
Run Code Online (Sandbox Code Playgroud)

fra*_*llo 9

我决定在这里为未来的读者做一个完整的答案.

花了几个小时在这个问题上,我意识到问题是我正在尝试做两件事:

  1. 扩展布局,这是一种需要在UI线程上进行设计的操作.
  2. 显示一个Dialog(ProgressDialog,实际上,但这不会改变结果),这可以仅从UI线程完成,因为Services不能显示任何Dialog.

因此,由于两个调用都来自UI线程(onCreate或AsyncTask没有区别,它仍然是UI线程),第一个阻止第二个调用正确显示.底线是:这个问题现在无法在Android中解决.让我们希望我们能够获得一些更好的API来与UI进行交互,因为我们有些糟糕.

我将通过更改布局并使其更轻(如果可能!)来解决此问题.感谢大家!


Joh*_*ker 8

我在创建一个沉重的视图时遇到了同样的问题,我所做的只是在xml文件中放置了一个linearlayout并在其上调用了setContentView,然后我在asynctask中创建了真实视图,并将视图dymanically添加到linearlayout.

这个方法似乎有效,我可以在此过程中进行进度对话.