【发布时间】:2018-05-23 08:17:12
【问题描述】:
我在 Xamarin 中做一个自定义渲染器。我不明白如何让它工作。我已按照以下说明进行操作: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/view#Consuming_the_Custom_Control
但是没有说明如何创建android视图
CustomRenderer.Droid.CameraPreview
如果我创建一个 Android 视图,它只是一个 cs 文件,而不是一个我也认为很奇怪的 .xaml。
我创建了一个空的 Android 视图类,我尝试从我的 android 渲染器将其设置为我的本机控件:
SetNativeControl(view);
但它会产生一个 TargetInvocationException。
这应该如何工作?
-------编辑-------
当我运行以下命令时,什么都没有发生,我希望在视图中绘制按钮。
public class CameraRenderer : ViewRenderer<Controls.CustomControl, MainApplication.Droid.CameraPreview>
{
private CameraPreview view;
private Context thisContext;
LayoutInflater inflater2;
protected override void OnElementChanged(ElementChangedEventArgs<Controls.CustomControl> e)
{
base.OnElementChanged(e);
view = new CameraPreview(thisContext);
inflater2 = (LayoutInflater)thisContext.GetSystemService(Context.LayoutInflaterService);
inflater2.Inflate(Resource.Layout.layout1, view);
SetNativeControl(view);
}
public CameraRenderer(Context context) : base(context)
{
thisContext = context;
}
}
public class CameraPreview : ViewGroup
{
public CameraPreview(Context context) : base(context)
{
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Button test"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
【问题讨论】:
-
应该是.cs文件。然后,您可以使用链接中解释的自定义控件:
local:CameraPreview。尝试逐一按照链接中的教程进行操作,如果它不适合您,请解释您不理解的内容。 -
@DennisSchröer 谢谢,我意识到我的错误。但是,我仍在为如何向我的 CameraPreview 添加控件而苦苦挣扎。我应该如何附加例如视图的按钮?
-
那么你需要另一个自定义控件。例如,一个名为
CameraWithButton的控件继承自RelativeLayout。您对它进行编码就像您刚刚对您的自定义CameraPreview进行编码一样。在它的构造函数中,将您的自定义CameraPreview和Button添加到Children。此链接有助于了解RelativeLayout中的定位如何工作:forums.xamarin.com/discussion/22902/… -
@DennisSchröer 如果我的 CameraPreview 根本不包含任何内容,我应该用它做什么?感觉这一步毫无意义。
-
@DennisSchröer 我真正想做的是在我的自定义渲染器中添加一个 SciChart 图表。