Oma*_*ada 9 c# xaml xamarin.android xamarin xamarin.forms
我需要一些帮助Android.Views.ViewGroup才能添加到XAML页面.
我有一个Xamarin项目,其解决方案结构如下所示:
请注意customViewGroup.aar我使用Xamarin Android绑定库添加到解决方案中.
AAR文件包含一个Android.Views.ViewGroup我想要显示的类,MyPage.xaml但我不知道如何做到这一点.我似乎无法找到适合这个确切用例的指南或代码示例(我也找不到涉及向Android.Views.ViewXamarin XAML页面添加简单的一个).
我已经找到了添加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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
要在 Xamarin.Forms 页面中包含本机控件,您需要创建自定义控件和平台呈现器。请参阅官方文档以获取完整演练。
简而言之,您首先在共享项目中声明一个新控件:
public class MyCustomViewControl : View
{
}
Run Code Online (Sandbox Code Playgroud)
现在,在 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还将使用渲染器在本机端设置事件等。
由于该属性,渲染器被 Xamarin.Forms 识别并注册,该属性可以与Renderer命名空间上方的 , 位于同一文件中:
[assembly: ExportRenderer (typeof(MyCustomViewControl), typeof(MyCustomViewRenderer))]
Run Code Online (Sandbox Code Playgroud)