我正在开展一个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'
答案 0 :(得分:4)
Android.Widget.AutoCompleteTextView
是来自Android的View
。
PCL解决方案:
您无法在Xamarin Forms(PCL)View's
上使用特定于平台的ContentPage
。
要使用特定于平台的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();
...