AlertDialog - 如何在事件发生后更新消息

AlertDialog - How to update message after an event happened

我正在尝试显示一个带有进度条的警告对话框和一条显示 "Bluetooth is connecting" 的消息。 我想在连接成功时将该文本更改为 "Bluetooth Connected"。

然而,在第二次调用警告对话框后,我得到一个错误

The specified child already has a parent. You must call removeView() on the child's parent first.

我发现了几个类似的问题,但还没有找到解决方案。

我的代码:

我先打电话

showProgressBar("Connecting to Bluetooth...");

然后,根据回调方法的结果,我尝试用不同的消息再次显示/更新警报对话框

  @Override
/*
* Callback method that is triggered once we have a result about the bluetooth connection
* */
public void isBluetoothConnected(boolean isConnected)
{
    if (isConnected)
    {
        showProgressBar("CONNECTED!");
    }
    else
    {
        showProgressBar("Bluetooth Not Connected");
    }
}

这就是我创建警报对话框的方式

public void showProgressBar(String loadingStatus)
{
    activity.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            if (progressDialog!=null)
            {
                progressDialog.dismiss();
            }

            progressDialog = getDialogProgressBar(loadingStatus).create();
            progressDialog.show();
        }
    });
}

public AlertDialog.Builder getDialogProgressBar(String loadingStatus)
{
    ProgressBar progressBar = new ProgressBar(context);
    if (builder == null) 
    {
        builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setMessage(loadingStatus);
        builder.setNegativeButton("Cancel", null);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        progressBar.setLayoutParams(lp);
        builder.setView(progressBar);
    }
    return builder;
}

我的问题是,当显示警告对话框时,我如何才能每次都更新显示的消息?

您需要创建一个包含 TextView 和进度条的 XML 布局文件,而不是在您的代码中对其进行实例化。

使用 dialog.setView(R.layout.yourLayout) 应用您的布局。

然后就可以用dialog.findViewById(R.id.yourTextViewID)得到想要的TextView了。检索到它后,您可以在视图上调用 setText(yourText)。

如果您选择这样做,则无需调用 dialog.setMessage(yourMessage)。

希望对您有所帮助。

如果你还在犹豫,可以看这篇:

https://developer.android.com/guide/topics/ui/declaring-layout

或者,您可以在对话框本身上设置消息。 (而不是生成器)

https://www.google.com/url?sa=t&source=web&rct=j&url=

试试这个

 @Override
/*
 * Callback method that is triggered once we have a result about the bluetooth connection
 * */
public void isBluetoothConnected(boolean isConnected)
{
    if (isConnected)
    {
        showProgressBar("CONNECTED!");
    }
    else
    {
        if(progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setMessage("Bluetooth Not Connected");
        } else {
            // handle
        }
    }
}