如何在 Xamarin.Forms 上使用 Android AutoCompleteTextView

2024-03-28

我正在研究一个Xamarin.forms项目但我需要使用Android.Widget.AutoCompleteTextView我该如何应用它? 当我尝试添加时AutoCompleteTextView UserNameAutoComplete; to ContentPage我收到以下错误:

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

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


Android.Widget.AutoCompleteTextView is a View来自安卓。


PCL的解决方案:

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

使用特定于平台的View你应该使用自定义渲染 https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/。 有一个博客文章 https://blog.xamarin.com/using-custom-controls-in-xamarin-forms-on-android/来自@JamesMontemagno,它展示了如何做你需要的事情。

这段代码是草稿范例请按原样使用它。

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.
        }
    }
}

共享项目的解决方案:

使用共享项目时可以使用原生嵌入 https://developer.xamarin.com/guides/xamarin-forms/user-interface/layouts/add-platform-controls/, like:

    ...
    var textView = new TextView (Forms.Context) { Text = originalText };
    stackLayout.Children.Add (textView);
    contentView.Content = textView.ToView();
    ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Xamarin.Forms 上使用 Android AutoCompleteTextView 的相关文章

随机推荐