【问题标题】:How to use Android AutoCompleteTextView on Xamarin.Forms如何在 Xamarin.Forms 上使用 Android AutoCompleteTextView
【发布时间】:2016-10-13 19:28:56
【问题描述】:

我正在处理Xamarin.forms 项目,但我需要使用Android.Widget.AutoCompleteTextView 我该如何应用它? 当我尝试将AutoCompleteTextView UserNameAutoComplete; 添加到ContentPage 时,出现以下错误:

Content = new StackLayout 
{                   
    VerticalOptions = LayoutOptions.Center,
    Padding = new Thickness(25),
    Children = 
    {
        UserNameAutoComplete,
        passwordEditor,
    }
};

无法从“Android.Widget.AutoCompleteTextView”转换为 'Xamarin.Forms.View'

【问题讨论】:

    标签: xamarin xamarin.android xamarin.forms


    【解决方案1】:

    Android.Widget.AutoCompleteTextView 是来自 Android 的 View


    PCL 解决方案:

    您不能在 Xamarin 表单 (PCL) ContentPage 上使用特定于平台的 View's

    要使用特定于平台的View,您应该使用custom render。 来自@JamesMontemagno 的blog post 显示了如何执行您需要的操作。

    此代码是草稿示例请照此使用。

    1 - 创建您自己的自定义 Xamarin.Forms 控件,该控件将在 Android 中呈现为 AutoCompleteTextView

    public class AutoCompleteView : View
    {   
        // Place need properties here.    
    }
    

    2 - 在 Android 项目中为 AutoCompleteView 添加渲染器:

    [assembly: ExportRenderer(typeof(AutoCompleteView), typeof(AutoCompleteViewRenderer))]
    namespace App.Droid
    {
        public class AutoCompleteViewRenderer : ViewRenderer<AutoCompleteView, AutoCompleteTextView>
        {    
            // Initialize the AutoCompleteTextView
            protected override void OnElementChanged (ElementChangedEventArgs<AutoComplete> e)
            {
                base.OnElementChanged (e);
    
                if (e.OldElement != null || this.Element == null)
                    return;
    
                var autoComplete = new AutoCompleteTextView(Forms.Context); 
                SetNativeControl (autoComplete);
            }
    
            // Use the control here.
            protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) {
                base.OnElementPropertyChanged (sender, e);
    
                if (this.Element == null || this.Control == null)
                  return;
    
                // variable this.Control is the AutoCompleteTextView, so you an manipulate it.
            }
        }
    }
    

    共享项目解决方案:

    使用共享项目时,可以使用Native Embedding,例如:

        ...
        var textView = new TextView (Forms.Context) { Text = originalText };
        stackLayout.Children.Add (textView);
        contentView.Content = textView.ToView();
        ...
    

    【讨论】:

    • 能否请您提供一个步骤或添加一些代码..谢谢
    • 感谢 jzeferion ..如果您熟悉自定义渲染,能否为您的答案添加代码包含步骤 ..
    • 我添加了一个简单的例子来解释渲染是如何工作的。有关更多详细信息,请阅读完整的博客文章。
    • 我正在尝试使用您的答案,实际上这个概念需要是如何在 xamarin .forms 上嵌入本机控件
    • 是的,这就是我发布的内容。我制作的示例和博客文章是关于如何在表单中使用本机控件。
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多