Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Android AutoCompleteTextView on Xamarin.Forms

I'm working on a Xamarin.forms project but i need to use Android.Widget.AutoCompleteTextView how can i apply that? When i am trying to add AutoCompleteTextView UserNameAutoComplete; to 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'

like image 701
Mohamad Mahmoud Avatar asked Jun 13 '16 11:06

Mohamad Mahmoud


1 Answers

Android.Widget.AutoCompleteTextView is a View from Android.


Solution for PCL:

You can't use platform specific View's on Xamarin Forms (PCL) ContentPage.

To use platform specific View you should use a custom render. There is a blog post from @JamesMontemagno that shows how to do what you need.

This code is draft exemple please use it as such.

1 - Create your own custom Xamarin.Forms control that will be renderered in Android as an AutoCompleteTextView:

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

2 - In 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 Shared Project:

When using Shared Project there is a possibility to use Native Embedding, like:

    ...
    var textView = new TextView (Forms.Context) { Text = originalText };
    stackLayout.Children.Add (textView);
    contentView.Content = textView.ToView();
    ...
like image 195
jzeferino Avatar answered Sep 30 '22 16:09

jzeferino