【问题标题】:Open new Activity from Xamarin Custom Renderer从 Xamarin 自定义渲染器打开新活动
【发布时间】:2020-06-13 20:32:39
【问题描述】:

这是我的第一个自定义渲染器项目,刚刚接触到 xamarin。我有一个相机自定义渲染器,并希望将图像预览(通过文件路径)传递给另一个活动以获取额外的功能,在 Android 中。 使用经典:

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

它会引发错误: -“this”中的第一个表示“错误 CS1503 参数 1:'CustomRenderer.Droid.CameraPageRenderer' 可以转换为 'Android.Content.Context'” -其次,在“StartActivity”中显示“错误 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);
        }

【问题讨论】:

    标签: c# xamarin custom-renderer


    【解决方案1】:

    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) { }
    

    【讨论】:

    • 谢谢!!!我希望我能给你投票。无论你在哪里,当它奏效时,感受我的拥抱和幸福的尖叫。我希望你有一个令人难以置信的生活。
    • @NatanOrtegaWhite 很高兴它成功了。如果答案正确,记得接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2021-04-04
    • 2018-07-29
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多