1

在我的应用程序中,我有一个自定义 AlertView,到目前为止效果很好。我可以第一次打开它,做我想做的,然后关闭它。如果我想再次打开它,我会得到

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

所以,这里有一些代码:

public Class ReadingTab
{
    ...
    private AlertDialog AD;
    ...
    protected override void OnCreate(Bundle bundle)
    {
         btnAdd.Click += delegate
         {
             if (IsNewTask)
             {
                 ...
                 AlertDialog.Builer adb = new AlertDialog.Builer(this);
                 ...
                 View view = LayoutInflater.Inflate(Resource.Layout.AlertDView15ET15TVvert, null);
                 adb.setView(view)
              }
              AD = adb.show();
         }
     }
 }         

那将是我的代码的粗略外观。btnAdd 内部还有两个按钮,其中一个(btnSafe)我AD.Dismiss()关闭警报对话框,adb.dispose()没有做任何事情。第一次工作正常,但是当我将其称为第二次时,调试器会AD = adb.show();出现上述异常。

那么我该怎么做才能从父级中删除对话?我在任何地方都找不到 removeView()。

4

1 回答 1

4

如果您设置AlertView一次然后在多个地方使用它(特别是如果您AlertView在不同的活动中使用相同的),那么您应该考虑创建一个静态AlertDialog类,然后您可以从所有地方调用它,并传入当前上下文每次你想显示它时作为参数。然后,当单击按钮时,您可以简单地关闭对话框并将实例设置为 null。这是一个基本示例:

internal static class CustomAlertDialog
{
    private static AlertDialog _instance;
    private const string CANCEL = @"Cancel";
    private const string OK = @"OK";
    private static EventHandler _handler;

    // Static method that creates your dialog instance with the given title, message, and context
    public static void Show(string title,
        string message,
        Context context)
    {
        if (_instance != null)
        {
            throw new Exception(@"Cannot have more than one confirmation dialog at once.");
        }

        var builder = new AlertDialog.Builder(context);
        builder.SetTitle(title);
        builder.SetMessage(message);

        // Set buttons and handle clicks
        builder.SetPositiveButton(OK, delegate { /* some action here */ });
        builder.SetNegativeButton(CANCEL, delegate { /* some action here */});

        // Create a dialog from the builder and show it
        _instance = builder.Create();
        _instance.SetCancelable(false);
        _instance.Show();
    }
}

从您的活动中,您可以像这样调用您的 CustomAlertDialog:

CustomAlertDialog.Show(@"This is my title", @"This is my message", this);
于 2013-05-24T19:46:36.997 回答