xamarin - 在 XF 5.0.0.2012 中将 Visual as Material 设置为 Xamarin.Forms Entry 控件时无法获取 Android 本机元素
问题描述
描述
当我们为入口设置材料设计时,我们无法在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; }
}
安卓渲染器
...
[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;
}
}
}
重现步骤
- 运行示例
- 在 Android 项目 -> 渲染器文件中,在下面的链接中添加断点。
if (renderer != null)
{
var nativeEditText = GetNativeEditText(renderer as ViewGroup);
if (nativeEditText != null && nativeEditText.Handle != IntPtr.Zero)
**Here** {
}
}
- 请参阅 GetNativeEditText 在 Visual as Material 时返回 null 值。
预期行为
必须在 Material Design 中返回原生元素。
实际行为
在材料设计中返回空值。
基本信息
- Xamarin.Forms:5.0.0.2012
- Xamarin.Forms.Visual.Material:5.0.0.2012
样本
https://github.com/MuneeshKumarG/Samples/tree/main/XF5Sample
解决方案
推荐阅读
- android - Android布局边框隐藏背景角
- spring - 从 Spring Boot 1.5 升级时为 Spring Boot 2.0 acuator 框架配置安全性
- python - Pytest 夹具返回倍数
- python - 使用 self vs cls 访问 unittest 中的变量
- machine-learning - 如何定义自动训练何时停止?
- git - 如何将工作转移到新分支并删除所有提交历史记录?
- java - 在执行其他 Java 类的静态块之前是否已加载和初始化 Sping Bean?
- c# - 在 .net core MVC 中创建 JSON
- java - JPA - 创建连接多个表的平面实体
- amazon-ec2 - 如何使用 Cloud Formation 或 AWS CLI 将扩展策略添加到 Auto Scaling 组