【发布时间】:2018-11-06 14:33:49
【问题描述】:
我想在 ContentPage 中添加一个 Android.Widget.RelativeLayout。为此,我遵循了多个在线示例:
Xamarin Forms Custom Renderer for Android not displaying
Adding an "Android.Views.ViewGroup" to a Xamarin XAML page
和其他人。
但我无法让它工作。
在我的共享项目中,我有:
namespace SharedProject
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
....
}
空格
namespace SharedProject
{
public class MyCustomViewControl : View
{
public MyCustomViewControl()
{
}
}
}
以及正在呈现的 MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:SharedProject="clr-namespace:SharedProject;assembly=SharedProject"
x:Class="SharedProject.MainPage">
<ContentPage.Content>
<StackLayout>
<SharedProject:MyCustomViewControl
HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
在 MonoAndroid 项目中:
[assembly: ExportRenderer(typeof(MyCustomViewControl), typeof(MyCustomViewRenderer))]
namespace SharedProject.Mobile.Droid
{
public class MyCustomViewRenderer : ViewRenderer<MyCustomViewControl, RelativeLayout>
{
public MyCustomViewRenderer(Context context) : base(context)
{
}
private Android.Widget.RelativeLayout rlMainContainer;
protected override void OnElementChanged(ElementChangedEventArgs<MyCustomViewControl> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
{
return;
}
rlMainContainer = new RelativeLayout(Context);
rlMainContainer.SetMinimumHeight(50);
rlMainContainer.SetMinimumWidth(100);
rlMainContainer.LayoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
if (Control == null)
SetNativeControl(rlMainContainer);
MainActivity.instance.setActiveReader(Control);
}
}
}
在我的 MainActivity.OnCreate 我有:
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
instance = this;
LoadApplication(new App());
我期待在渲染 MainPage 时,也会根据 MainPage.xaml 和 OnElementChanged 将 rlMainContainer 添加到其中,但未请求 MyCustomViewRenderer 内部的任何内容(没有断点命中)。
我做错了什么?
【问题讨论】:
标签: xamarin xamarin.forms xamarin.android