C# 在XAML中创建和使用Android视图
下午好 我确信这个问题的答案就在那里——但我不知道在哪里,所以让我开始吧 我以前为Android平台和Windows平台开发过,但我很难理解如何使用Xamarin.Forms从XAML引用Android布局/活动。 我发现了使用本机控件和子类控件的示例,但我似乎无法将不同的概念结合起来,使XAML引用整个视图 任何帮助都将不胜感激C# 在XAML中创建和使用Android视图,c#,xamarin.android,xamarin.forms,C#,Xamarin.android,Xamarin.forms,下午好 我确信这个问题的答案就在那里——但我不知道在哪里,所以让我开始吧 我以前为Android平台和Windows平台开发过,但我很难理解如何使用Xamarin.Forms从XAML引用Android布局/活动。 我发现了使用本机控件和子类控件的示例,但我似乎无法将不同的概念结合起来,使XAML引用整个视图 任何帮助都将不胜感激 using Android.Content; using Android.Runtime; using Android.Util; using Android.Vie
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Views;
namespace PlatformControls.Droid
{
[Register("xxxxControl")]
public class xxxxControl : View
{
Context mContext;
#region Private Members
#endregion
#region Constructors
public xxxxControl(Context context)
: base(context)
{
init(context);
LayoutInflater mInflator = LayoutInflater.From(context);
View layout = mInflator.Inflate(Resource.Layout.GanttCellControlLayout, null, false);
// cannot addView() !?
// dont know what to do - other than attempt to drown myself in the toilet sink
}
public xxxxControl(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init(context);
}
public xxxxControl(Context context, IAttributeSet attrs, int d)
: base(context)
{
init(context);
}
#endregion
#region Public Properties
#endregion
#region Methods
#endregion
private void init(Context context)
{
mContext = context;
}
}
}
结果是;您仍然需要自定义渲染器
也许您过去需要一个自定义的渲染器,但现在本地嵌入可用了,情况似乎不再是这样了。 这样的解决方案是可能的
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:androidLocal="clr-namespace:NativeControls.Droid;assembly=NativeControls.Droid;targetPlatform=Android"
xmlns:formsAndroid="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.Platform.Android;targetPlatform=Android"
x:Class="Wrappers.CP.CustomControlWrapper">
<ContentView.Content>
<androidLocal:MyView x:Arguments="{x:Static formsAndroid:Forms.Context}"
Text ="I am rendered by an Android custom control"/>
</ContentView.Content>
</ContentView>
作为一个相对新手,上面代码中MyView对象的类型似乎并不十分明显。
一个似乎有效的答案是,它应该继承自LinearLayout。
然后编写如下代码
// Get the UI controls from the loaded layout:
Inflate(Context, Resource.Layout.MyView, this);
this.myText = FindViewById<TextView>(Resource.Id.SomeContent);
// Add controls to the layout here if needed
var layout = FindViewById<LinearLayout>(Resource.Id.MyView_outerlayout);
可以添加到上面示例中的init函数中,以获取对布局中控件的引用或获取布局,以便添加其他控件