如何解决在 XF 5.0.0.2012 中将 Visual 设置为 Xamarin.Forms Entry 控件时无法获取 Android 本机元素 说明重现步骤预期行为实际行为基本信息示例
说明
当我们为入口设置 Material design 时,我们无法在 android 中获取原生元素。
没有材料设计,我们可以得到原生的EditText。
在 XF 中:4.8.0.1687。这工作正常
XAML
<local:CustomView >
<local:CustomView.Input>
<Entry Visual="Material"/>
</local:CustomView.Input>
</local:CustomView>
C#
public class CustomView : TemplatedView
{
public CustomView()
{
this.ControlTemplate = new ControlTemplate(typeof(StackLayout));
}
public View Input { get; set; }
}
Android 渲染器
...
[assembly: Forms.ExportRenderer(typeof(CustomView),typeof(CustomVieWrenderer))]
namespace XF5Sample.Droid
{
public class CustomVieWrenderer : VieWrenderer<CustomView,View>
{
private CustomView customView;
public CustomVieWrenderer(global::Android.Content.Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomView> e)
{
base.OnElementChanged(e);
var element = e.NewElement;
customView = element as CustomView;
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (Platform.GetRenderer(customView.Input) == null)
{
Platform.SetRenderer(customView.Input,Platform.CreateRendererWithContext(customView.Input,Context));
}
var renderer = Platform.GetRenderer(customView.Input);
if (renderer != null)
{
var nativeEditText = GetNativeEditText(renderer as ViewGroup);
if (nativeEditText != null && nativeEditText.Handle != IntPtr.Zero)
{
}
}
}
internal static EditText GetNativeEditText(ViewGroup viewGroup)
{
EditText editText = null;
if (editText == null && viewGroup is ViewGroup)
{
var childCount = viewGroup.ChildCount;
for (int i = 0; i < childCount; i++)
{
var child = viewGroup.GetChildAt(i);
if (child is EditText)
{
editText = child as EditText;
}
else if (child is ViewGroup)
{
editText = GetNativeEditText(child as ViewGroup);
}
else
{
return editText;
}
if (editText != null)
{
break;
}
}
}
return editText;
}
}
}
重现步骤
if (renderer != null)
{
var nativeEditText = GetNativeEditText(renderer as ViewGroup);
if (nativeEditText != null && nativeEditText.Handle != IntPtr.Zero)
**Here** {
}
}
- 参见 GetNativeEditText 返回 null 值,而 Visual as Material。
预期行为
必须在 Material design 中返回原生元素。
实际行为
在材料设计中返回空值。
基本信息
- Xamarin.Forms:5.0.0.2012
- Xamarin.Forms.Visual.Material:5.0.0.2012
示例
https://github.com/MuneeshKumarG/Samples/tree/main/XF5Sample
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。