我有一个主要活动,其中有一个按钮和图像视图控件。我可以将从设备存储中选择的图片显示到Imageview。但是当我尝试从Intent获取图像URI时会发生错误。
我的按钮点击事件代码
private void TakeAPicture (object sender, EventArgs eventArgs)
{
var imageIntent = new Intent ();
imageIntent.SetType ("image/*");
imageIntent.SetAction (Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(imageIntent, "Select Image"),0);
}
OnActivityresult覆盖代码
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult (requestCode, resultCode, data);
if (resultCode == Result.Ok) {
Uri selectedImageUri = data.GetData();// code to get URI and I am stuck here
string selectedImagePath = ImageFilePath.getPath(context, selectedImageUri);
var imageView =
FindViewById<ImageView> (Resource.Id.imageView1);
UploadImage (selectedImagePath);
}
完整错误文字
Error CS1061: 'Android.Content.Intent' does not contain a definition for 'GetData' and no extension method 'GetData' accepting a first argument of type 'Android.Content.Intent' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Capture)
为什么我收到此错误。 Android intent中是否没有名为GetData()的方法,或者我缺少任何特定的库?
答案 0 :(得分:2)
onButtonclick(); -
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, SELECT_FILE);
onActivityResult(); -
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgPath = cursor.getString(columnIndex);
cursor.close();
答案 1 :(得分:1)
您可以使用此方法获取完整路径 -
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
picturePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
答案 2 :(得分:1)
Xamarin中有一种典型模式,它将Android Java组件getter映射到C#get only(set not implemented)属性。
在您的情况下,Java代码android.content.Intent.getData映射到Intent.Data的C#属性,如下所示:
namespace Android.Content
{
[Register ("android/content/Intent", DoNotGenerateAcw = true)]
public class Intent : Object, IParcelable, ICloneable, IJavaObject, IDisposable
public virtual Uri Data {
[Register ("getData", "()Landroid/net/Uri;", "GetGetDataHandler")] ...
您还会发现其他Java getter(如getComponent)映射到&#34; Component&#34;的属性。如下:
public virtual ComponentName Component {
[Register ("getComponent", "()Landroid/content/ComponentName;", "GetGetComponentHandler")]
get {
if (Intent.id_getComponent == IntPtr.Zero) {
Intent.id_getComponent = JNIEnv.GetMethodID (Intent.class_ref, "getComponent", "()Landroid/content/ComponentName;");
} ...
记住这个Xamarin的Java到C#映射模式将帮助您将Java代码转换为C#,并避免卡住: - )。
如果您使用Xamarin工作室,请在OSX上使用Cmd + D或在Windows上使用F12检查Xamarin源,同时注意单词&#39; Intent&#39;在您的源代码中,它将增加您对此映射如何工作的理解深度。