Xamarin.Android:ProgressDialog没有显示出来

时间:2018-05-24 13:42:29

标签: android android-asynctask xamarin.android async-await progressdialog

我在显示 ProgressDialog

时遇到问题

以下代码段在示例中显示了我的代码:

public override void OnActivityCreated(Bundle savedInstanceState)
{
    base.OnActivityCreated(savedInstanceState);

    progressDialog = new ProgressDialog(Context);
    progressDialog.SetCancelable(false);
    progressDialog.SetMessage("Saving ...");
}


private void Method()
{
    progressDialog.Show();

    var testDialog = progressDialog.IsShowing;

    SaveImage();
}


private void SaveImage()
{
    // does lot 
    ...
    // especially this method takes some time
    mutableBitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
}

我创建了一个ProgressDialog,我想在调用 SaveImage 方法之前显示它(并在 SaveImage 完成时取消它)。

我的问题是在 SaveImage 方法完成之前不会显示ProgressDialog。

在调试模式下, progressDialog.IsShowing true ,在调用 SaveImage -Method之前,但不会显示。< / p>

2 个答案:

答案 0 :(得分:0)

你必须将你的IO相关代码转移到后台线程,你可以使用asynctask来实现这个

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

private String resp;
ProgressDialog progressDialog;

@Override
protected String doInBackground(String... params) {
    saveImage();
}


@Override
protected void onPostExecute(String result) {
    // execution of result of Long time consuming operation
    progressDialog.dismiss();
}


@Override
protected void onPreExecute() {
    progressDialog = ProgressDialog.show(getContext(),
            "ProgressDialog",
            "Loading");
}
}

答案 1 :(得分:0)

我找到了一个适合我的解决方案:

private async void Method()
{
    progressDialog.Show();

    var thread = new System.Threading.Thread(new ThreadStart(delegate
    {
        SaveImage();
    }));
    thread.Start();

    while(thread.ThreadState == ThreadState.Running)
    {
        await Task.Delay(100);
    }

    progressDialog.Dismiss();
}

与此同时,我将此代码外包给public static class ThreadHelper,只需要一个Action(在本例中为 SaveImage())和一个ProgressDialog作为参数。