点击事件只需写这段代码
case R.id.iv_attachment_pic:
CharSequence[] names = { "From Galary", "From Camera" };
new AlertDialog.Builder(context)
.setTitle("Select an option")
.setItems(names, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
// TODO Auto-generated method stub
if (pos == 0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GET_GAL_IMG);
} else {
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, GET_CAM_IMG);
}
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).create().show();
break;
并将其恢复到主要活动只需使用这样的 onactivity 结果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case 2:
if (resultCode == -1) {
encodedImageString = null;
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
bmp_image = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
iv_attachment.setImageBitmap(bmp_image);
if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
byte[] image = baos.toByteArray();
encodedImageString = Base64.encodeToString(image,
Base64.DEFAULT);
} else {
System.out.println("Compreesion returned false");
Log.d("Compress", "Compreesion returned false");
}
}
break;
case 3:
if (resultCode == -1) {
encodedImageString = null;
bmp_image = null;
Bundle extras = intent.getExtras();
bmp_image = (Bitmap) extras.get("data");
iv_attachment.setImageBitmap(bmp_image);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
byte[] image = baos.toByteArray();
encodedImageString = Base64.encodeToString(image,
Base64.DEFAULT);
} else {
System.out.println("Compreesion returned false");
Log.d("Compress", "Compreesion returned false");
}
}
break;
}
}
这里 GET_GAL_IMG 和 GET_CAM_IMG 是两个变量,iv_attachment 是您主要活动中的图像视图