众所周知,Maui的前身是Xamarin,正如它的老大哥,Maui同样支持Render。但是我在使用Maui创建axml布局文件用来显示文本时,发现文本根本显示不了,如图所示:
同样的代码在Xamarin中使用Render可以显示,而在Maui中却显示不来。
Render:
public class ViewRenderer : ViewRenderer
{
Context baseContext;
static Views.View View;
public NoticeContentCardViewRenderer(Context context) : base(context)
{
baseContext = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
try
{
base.OnElementChanged(e);
var activity = (Activity)MainActivity.Instance;
if (View == null)
{
View = activity.LayoutInflater.Inflate(Resource.Layout.TestLayout, this, false);
}
SetNativeControl(View);
}
}
catch (Exception ex)
{
Log.Debug($"{ex}");
}
}
protected override void Dispose(bool disposing)
{
try
{
base.Dispose(disposing);
}
catch (Exception ex)
{
Log.Debug($"{ex}");
}
}
}
TestLayout.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:maui="clr-namespace:Microsoft.Maui.Controls;assembly=Microsoft.Maui.Controls"
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello,World"
android:textSize="50sp"
android:textColor="@android:color/holo_red_light"
android:cursorVisible="true"/>
</LinearLayout>
无奈,只能尝试按照Maui的官网步骤,将Render迁移到Handler。
Handler:
public partial class ViewHandler : ViewHandler<MyView, Views.View>
{
Context baseContext;
static Views.View View;
public static PropertyMapper<MyView, ViewHandler> PropertyMapper = new PropertyMapper<MyView, ViewHandler>(ViewHandler.ViewMapper)
{
};
public ViewHandler() : base(PropertyMapper)
{
}
protected override Views.View CreatePlatformView() => new PlatformView (Context);
protected override void ConnectHandler(Views.View platformView)
{
base.ConnectHandler(platformView);
var activity = (Activity)MainActivity.Instance;
if (View == null)
{
View = activity.LayoutInflater.Inflate(Resource.Layout.TestLayout, null, false);
}
activity.SetContentView(View);
}
protected override void DisconnectHandler(Views.View platformView)
{
// Perform any native view cleanup here
platformView.Dispose();
base.DisconnectHandler(platformView);
}
运行成功~~~
不知道是否可以凭借Render显示文本,反正我试了半天没试出来,看样子是Maui要把Render给优化掉了吗【苦笑】