我有一个带有默认图像的 imageview
,我希望当用户单击 imageview 打开图像选择器然后他从 sdcard 选择他的图像然后图像在 imageview 上,
这是我的图片 View
xml
<ImageView
android:id="@+id/ivImage"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="10dip"
android:contentDescription="@string/iv_undefinedImage"
android:src="@drawable/undefinedimage" />
Java
ImageView iv ;
iv_image = (ImageView)findViewById(R.id.iv_signup_image);
iv_image.setOnClickListener(this);
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_signup_image:
break;
}
我想这就是你要找的
if (Environment.getExternalStorageState().equals("mounted")) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(
Intent.createChooser(
intent,
"Select Picture:"),
requestCode);
}
并处理回调
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Bitmap photo = getPreview(selectedImagePath);
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(proj[0]);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
public Bitmap getPreview(String fileName) {
File image = new File(fileName);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1)) {
return null;
}
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / 64;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
希望对你有帮助