xamarin 未定义ImagePicker主活动示例

ipakzgxi  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(108)

已按照以下链接添加ImagePicker
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/photo-picker
此处,对于Android实现,问题是MainActivity.cs中未定义示例

[assembly: Dependency(typeof(PicturePickerImplementation))]

namespace DependencyServiceSample.Droid
{
    public class PicturePickerImplementation : IPicturePicker
    {
        public Task<Stream> GetImageStreamAsync()
        {
            // Define the Intent for getting images
            Intent intent = new Intent();
            intent.SetType("image/*");
            intent.SetAction(Intent.ActionGetContent);

            // Start the picture-picker activity (resumes in MainActivity.cs)
            MainActivity.Instance.StartActivityForResult(
                Intent.CreateChooser(intent, "Select Picture"),
                MainActivity.PickImageId);

            // Save the TaskCompletionSource object as a MainActivity property
            MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>();

            // Return Task object
            return MainActivity.Instance.PickImageTaskCompletionSource.Task;
        }
    }
}

并且MainActivity没有示例字段,是否有其他方法来获取示例?

public class MainActivity : FormsAppCompatActivity
{
    ...
    // Field, property, and method for Picture Picker
    public static readonly int PickImageId = 1000;

    public TaskCompletionSource<Stream> PickImageTaskCompletionSource { set; get; }

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

        if (requestCode == PickImageId)
        {
            if ((resultCode == Result.Ok) && (intent != null))
            {
                Android.Net.Uri uri = intent.Data;
                Stream stream = ContentResolver.OpenInputStream(uri);

                // Set the Stream as the completion of the Task
                PickImageTaskCompletionSource.SetResult(stream);
            }
            else
            {
                PickImageTaskCompletionSource.SetResult(null);
            }
        }
    }
}
oaxa6hgo

oaxa6hgo1#

MainActivity类添加以下内容:

internal static MainActivity Instance { get; private set; }

protected override void OnResume()
{
    Instance = this;
    base.OnResume();
}

还要感谢@SushiHangover在这里给出的答案,它描述了如何初始化Instance对象。
很可能是文档缺少了这一点。

cbeh67ev

cbeh67ev2#

缺少静态变量定义及其赋值。
将名为Instance的静态变量添加到MainActivity类:

public static Activity Instance;

然后在OnResume覆盖中分配它:

protected override void OnResume()
{
    Instance = this;
    base.OnResume();
}

相关问题