How to use Android AutoCompleteTextView on Xamarin.Forms

I am working on a Xamarin.forms project, but I need to use Android.Widget.AutoCompleteTextView , how can I apply this? When I try to add AutoCompleteTextView UserNameAutoComplete; in ContentPage , I get the following error:

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

cannot convert from 'Android.Widget.AutoCompleteTextView' to 'Xamarin.Forms.View'

+6
source share
1 answer

Android.Widget.AutoCompleteTextView is a View from Android.


PCL Solution:

You cannot use View's specific platform for Xamarin Forms (PCL) ContentPage .

To use a specific View platform, you must use personalized rendering . There is a blog post from @JamesMontemagno that shows how to do what you need.

This code is a rough example, please use it as such.

1 - Create your own Xamarin.Forms control, which will display in Android as AutoCompleteTextView :

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

2 - In an Android project, add a renderer for 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. } } } 

Solution for a common project:

When using the Shared Project, it is possible to use Native Embedding , for example:

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

All Articles