Xamarin 表单 ->System.MissingMethodException:找不到 [Interface] 的默认构造函数 [英] Xamarin Forms -> System.MissingMethodException: Default constructor not found for [Interface]

查看:38
本文介绍了Xamarin 表单 ->System.MissingMethodException:找不到 [Interface] 的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Xamarin.Forms 上使用依赖项服务时收到此错误.我已经看到了涉及 iOS 和链接器的此错误的答案.但是,我在 Android 上运行它并且链接器已关闭.

I am receiving this error when using the Dependency Service on a Xamarin.Forms. I have seen answers to this error that involve iOS and the Linker. However, I am running this on Android and the Linker is off.

它告诉我的构造函数在 PCL 中找不到接口的默认构造函数.

The constructor it is telling me it cannot find the default constructor for the Interface in the PCL.

我已经搜索和调试了几个小时.哪些事情可能会导致此错误?我很确定我的 DependencyService 实现是正确的,所以我觉得它有些不同.

I have been searching and debugging this for hours. What are some things that could be causing this error? I am pretty sure my DependencyService Implementations are correct so I feel like it is something different.

这是我的相关代码.

安卓

[assembly: Xamarin.Forms.Dependency(typeof(TextRecognition))]
namespace DiabetesAPP.Droid
{
    [Preserve(AllMembers = true)]
    [Activity(Label = "TextRecognition", Theme = "@style/Theme.AppCompat.Light.NoActionBar", MainLauncher = true)]
    public class TextRecognition : AppCompatActivity, ISurfaceHolderCallback, IProcessor, ITextRecognition
    {
        private SurfaceView cameraView;
        private TextView textView;
        private CameraSource cameraSource;
        public string Resultados;
        private const int RequestCameraPermissionID = 1001;

        protected override void OnCreate(Bundle savedInstanceState)
        {

            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Main);
            cameraView = FindViewById<SurfaceView>(Resource.Id.surface_view);
            textView = FindViewById<TextView>(Resource.Id.txtview);

            TextRecognizer textRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();
            if (!textRecognizer.IsOperational)
            {
                Log.Error("Main Activity", "Detector dependencies are not yet available");
            }
            else
            {
                cameraSource = new CameraSource.Builder(ApplicationContext, textRecognizer)
                    .SetFacing(CameraFacing.Back)
                    .SetRequestedFps(2.0f)
                    .SetRequestedPreviewSize(1280, 1024)
                    .SetAutoFocusEnabled(true)
                    .Build();

                cameraView.Holder.AddCallback(this);
                 textRecognizer.SetProcessor(this);
            }

            Android.Widget.Button logonButton = FindViewById<Android.Widget.Button>(Resource.Id.button_send);
            logonButton.Click += LogonButton_Click;
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            switch (requestCode)
            {
                case RequestCameraPermissionID:
                    {
                        if (grantResults[0] == Android.Content.PM.Permission.Granted)
                        {
                           cameraSource.Start(cameraView.Holder);
                        }
                    }
                    break;
            }
        }

        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {

        }

        public void SurfaceCreated(ISurfaceHolder holder)
        {
            if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[]
                {
                    Android.Manifest.Permission.Camera
                }, RequestCameraPermissionID);
                return;
            }
           cameraSource.Start(cameraView.Holder);
        }

        public void SurfaceDestroyed(ISurfaceHolder holder)
        {
            cameraSource.Stop();
        }

        public void ReceiveDetections(Detections detections)
        {
            SparseArray items = detections.DetectedItems;
            if (items.Size() != 0)
            {
                textView.Post(() =>
                {
                    StringBuilder strBuilder = new StringBuilder();
                    for (int i = 0; i < items.Size(); i++)
                    {
                        strBuilder.Append(((TextBlock)items.ValueAt(i)).Value);
                        strBuilder.Append("\n");
                    }
                    textView.Text = strBuilder.ToString();
                    Resultados = strBuilder.ToString();
                });
            }
        }

        private void LogonButton_Click(object sender, EventArgs e)
        {
            //Toast.MakeText(this, "Hello from " + Resultados, ToastLength.Long).Show();
            //Intent data = new Intent(this, typeof(TextRecognition));
            //SetResult(Result.Ok, data);
            //// MessagingCenter.Send((DiabetesAPP.App)Xamarin.Forms.Application.Current, "OpenPage", "You send message:" + Resultados);
            //// MessagingCenter.Send<DiabetesAPP.App, string>(DiabetesAPP.App.Current as App, "OpenPage", "You send message:" + Resultados);
            //MessagingCenter.Send((DiabetesAPP.App)Xamarin.Forms.Application.Current, "OpenPage", "You send message:" + Resultados);
            Toast.MakeText(this, Resultados, ToastLength.Short).Show();

            MessagingCenter.Send<App, string>(App.Current as App, "OpenPage", "You send message:" + Resultados);


            Finish();
        }

        public void Release()
        {

        }

        public void LaunchActivityInAndroid()
        {
            Activity activity = Forms.Context as Activity;
            var intent = new Intent(Forms.Context, typeof(TextRecognition));
            activity.StartActivity(intent);
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);


            switch (resultCode)
            {
                case Result.Ok:
                    break;
            }

            Finish();
        }



        public interface ITextRecognition
        {

        }

//Update code - 16/09/2020
        public TextRecognition()
        {

        }


    }
}

在 Xamarin.Form 页面中实现

[assembly: Xamarin.Forms.Dependency(typeof(ITextRecognition))]
namespace DiabetesAPP.Views.FoodMenu
{

    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class FoodMenu : ContentPage
    {
        public FoodMenu()
        {
            InitializeComponent();
        }

        async void Food_ManualEntry(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new SearchFood());
        }

        public void Food_CameraEntry(object sender, EventArgs e)
        {
            Xamarin.Forms.DependencyService.Register<ITextRecognition>();
            DependencyService.Get<ITextRecognition>().LaunchActivityInAndroid();

        }

        public interface ITextRecognition
        {
            void LaunchActivityInAndroid();
        }

    }
}

错误:System.MissingMethodException:未找到类型 DiabetesAPP.Views.FoodMenu.FoodMenu+ITextRecognition 的默认构造函数

出了什么问题?

推荐答案

Android 项目中不需要创建新的 ITextRecognition 接口,你应该使用您在 Xamarin.forms 项目中创建的界面.

You don't need to create a new ITextRecognition interface in Android project, you should use the interface which you created in the Xamarin.forms projet.

另外,最好不要在 FoodMenu 类中创建接口.

Also, it's better not to create the interface inside the FoodMenu class.

代码示例如下:

在 Xamarin.Forms 中:

In Xamarin.Forms:

namespace App384
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class FoodMenu : ContentPage
    {
        public FoodMenu()
        {
            InitializeComponent();
        }

        public void Food_CameraEntry(object sender, EventArgs e)
        {
            Xamarin.Forms.DependencyService.Register<ITextRecognition>();
            DependencyService.Get<ITextRecognition>().LaunchActivityInAndroid();

        }
    }

    public interface ITextRecognition
    {
        void LaunchActivityInAndroid();
    }
}

在 Xamarin.Android 项目中:

In Xamarin.Android project:

[assembly: Xamarin.Forms.Dependency(typeof(TextRecognition))]
namespace App384.Droid
{
    [Preserve(AllMembers = true)]
    [Activity(Label = "TextRecognition", Theme = "@style/Theme.AppCompat.Light.NoActionBar", MainLauncher = true)]
    public class TextRecognition : AppCompatActivity, ITextRecognition
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public void LaunchActivityInAndroid()
        {
            Console.WriteLine("LaunchActivityInAndroid");
        }

    }
}

我已经上传了这里的测试演示,您可以查看.

I have uploaded test demo here and you can check.

参考:Xamarin.Forms依赖服务介绍

这篇关于Xamarin 表单 ->System.MissingMethodException:找不到 [Interface] 的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆