我需要一些帮助才能将Android.Views.ViewGroup
添加到XAML页面。
我有一个Xamarin项目,其解决方案结构如下所示:
请注意我使用Xamarin Android绑定库添加到解决方案中的customViewGroup.aar
。
AAR文件包含Android.Views.ViewGroup
类,我想在MyPage.xaml
上显示,但我不知道如何操作。我似乎无法找到适合这个确切用例的指南或代码示例(也找不到涉及向Xamarin XAML页面添加简单Android.Views.View
的示例)。
我找到了将Android.Views.ViewGroup
添加到原生Android应用程序(使用Java和XML)的示例,但没有显示如何将其添加到Xamarin XAML页面。
请帮忙!
我要包含一些源代码,以便您可以看到我尝试过的内容:
MyPage.xaml
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.Views.MyPage"
xmlns:vm="clr-namespace:App1.ViewModels;"
xmlns:androidWidget="clr-namespace:Com.CustomAAR;assembly=Com.CustomAAR;targetPlatform=Android"
xmlns:formsAndroid="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"
Title="{Binding Title}">
<ContentPage.Content>
<ContentView x:Name="contentViewParent">
<androidWidget:MyCustomViewGroup x:Arguments="{x:Static formsandroid:Forms.Context}">
</androidWidget:MyCustomViewGroup>
</ContentView>
<!--<ContentView
IsVisible="True"
IsEnabled="True"
BindingContext="{Binding MyCustomViewGroup}">
</ContentView>-->
</ContentPage.Content>
</ContentPage>
MyPage.xaml.cs
public partial class MyPage : ContentPage
{
MyCustomViewGroupModel viewModel;
public MyPage()
{
InitializeComponent ();
}
public MyPage(MyCustomViewGroupModel viewModel)
{
InitializeComponent();
#if __ANDROID__
NativeViewWrapper wrapper = (NativeViewWrapper)contentViewParent.Content;
MyCustomViewGroup myCustomViewGroup = (MyCustomViewGroup)wrapper.NativeView;
//myCustomViewGroup = new MyCustomViewGroup(Android.App.Application.Context);
myCustomViewGroup.SomeAction("");
#endif
BindingContext = this.viewModel = viewModel;
}
}
答案 0 :(得分:1)
要在Xamarin.Forms页面中包含本机控件,您需要创建自定义控件和平台渲染器。有关完整演练,请参阅official documentation。
首先,您要在共享项目中声明一个新控件:
public class MyCustomViewControl : View
{
}
现在,在Android项目中,您将创建一个自定义渲染器,它将使用您的自定义Android视图进行原生显示:
public class MyCustomViewRenderer : ViewRenderer<MyCustomViewControl, MyCustomViewGroup>
{
MyCustomViewGroup viewGroup;
public MyCustomViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<MyCustomViewControl> e)
{
base.OnElementChanged(e);
if (Control == null)
{
viewGroup= new MyCustomViewGroup(Context);
SetNativeControl(viewGroup);
}
}
}
您还将使用渲染器在本机端设置事件等。
渲染器由Xamarin.Forms识别和注册,这要归功于该属性,该属性可以与命名空间上方的Renderer
位于同一文件中:
[assembly: ExportRenderer (typeof(MyCustomViewControl), typeof(MyCustomViewRenderer))]