ViewRenderer.SetNativeControl - 指定的 child 已经有一个 parent

ViewRenderer.SetNativeControl - The specified child already has a parent

我尝试使用此渲染器:

using System;
using Android.Content;
using Android.Views;
using Android.Widget;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(AutoComplete), typeof(xmr_cross_test.Custom_controls.AutoCompleteRenderer))]
namespace xmr_cross_test.Custom_controls
{
    public class AutoCompleteRenderer : ViewRenderer<AutoComplete, AutoCompleteTextView>
    {
        public AutoCompleteRenderer()
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<AutoComplete> e)
        {
            base.OnElementChanged(e);
            AutoComplete autocompletview = (AutoComplete)this.Element;

            var inflatorservice = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
            var containerView = inflatorservice.Inflate(Resource.Layout.autocomplete_entry, null, false);

            var autoCompleteTextView = containerView.FindViewById<AutoCompleteTextView>(Resource.Id.autocomplete_textview);
            var autoCompleteOptions = new String[] { "Hello", "Hey", "Bonjour" };
            var adapter = new ArrayAdapter<String>(Context, Resource.Layout.list_item, autoCompleteOptions);
            autoCompleteTextView.Hint = "e.g. Hey";
            autoCompleteTextView.Adapter = adapter;
            autoCompleteTextView.TextChanged += (sender, args) =>
            {
                autocompletview.AutoCompleteText = autoCompleteTextView.Text;
            };

            if (e.OldElement == null)
            {
                // perform initial setup
                base.SetNativeControl(autoCompleteTextView); //exception here
            }
        }
    }
}

但是绑定异常::

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

在这种情况下,child 是什么以及如何解决它?

PS: 可以在代码资源中添加引用,如果需要,可以添加 AutoComplete class。

所指的'child'是autoCompleteTextView

您在 XML 中创建自动完成(然后使用 findViewById 找到它)。这意味着自动完成已经附加到 XML 树。它的父级是它嵌套的视图组。

当您调用 base.SetNativeControl(autoCompleteTextView); 时,您试图将相同的视图添加到树中的第二个位置,就像自然界中的一棵真正的(木头)树一样,同一片叶子不能从两个树枝长出一次。

您的选项已使用糟糕的 hacky 例程从其现有父项中删除:

autoCompleteTextView.RemoveFromParent(); //xamarin

这相当于本机 Android 上的以下代码:

autoCompleteTextView.getParent().removeView(base);

或者以编程方式创建自动完成,然后按照您已经在尝试的方式附加它

(或者您的基础 dom 树允许您以编程方式移动节点。我不熟悉 xamarin)