从 Xamarin Custom Renderer 打开新的 Activity

Open new Activity from Xamarin Custom Renderer

这是我的第一个自定义渲染器项目,刚刚开始使用 xamarin.我有一个 Camera Custom Renderer,并且想将图像预览(通过文件路径)传递给另一个 activity 以获得额外的功能,在 Android 中。 使用经典:

            Intent intent = new Intent(this, typeof(ResultPage));
        StartActivity(intent);

它抛出错误: - "this" 中的第一个说 "error CS1503 argument 1: 'CustomRenderer.Droid.CameraPageRenderer' canto be converted to 'Android.Content.Context'" -其次,在 "StartActivity" 中表示 "Error CS0103 The name 'StartActivity' doesn't exist in the actual context 'CustomRenderer.Android'"

这是它应该去的方法:

        async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        camera.StopPreview();

        var image = textureView.Bitmap;

        try
        {
            var absolutePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
            var folderPath = absolutePath + "/Images";
            var filePath = System.IO.Path.Combine(folderPath, string.Format("image_{0}.jpg", Guid.NewGuid()));

            var fileStream = new FileStream(filePath, FileMode.Create);
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, fileStream);
            fileStream.Close();

            image.Recycle();

            var intent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile);
            var file = new Java.IO.File(filePath);
            var uri = Android.Net.Uri.FromFile(file);
            intent.SetData(uri);
            MainActivity.Instance.SendBroadcast(intent);

            CameraPageRenderer cameraPageRenderer = this;
            Intent intent = new Intent(this, typeof(ResultPage));
            StartActivity(intent);

        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(@"               ", ex.Message);
        }

CustomRenderer 不是 Android Context。您需要检索当前 Android Context 并使用它:

var context = this.Context;
Intent intent = new Intent(context, typeof(ResultPage));
context.StartActivity(intent);

请记住,您的自定义渲染器需要实现接受 Context 作为参数的参数化构造函数,才能使其正常工作:

public MyCustomRenderer(Context context) : base(context) { }