網上找了一些代碼,我再小米手機上測試,發現還是有的不是很好用,所以找了資料,把代碼貼出來分享一下。
[java]
public final static int CONSULT_DOC_PICTURE = 1000;
public final static int CONSULT_DOC_CAMERA = 1001;
private int SELECT_PICTURE = 0;
private int SELECT_CAMERA = 1;
private ImageView iv;
private Bitmap bmp;
private Uri outputFileUri;
[java]
private OnClickListener cameraClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CharSequence[] items = { "相冊", "相機" };
new AlertDialog.Builder(getActivity()).setTitle("選擇圖片來源").setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == SELECT_PICTURE) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "選擇圖片"), CONSULT_DOC_PICTURE);
} else {
File file = new File(Environment.getExternalStorageDirectory(), "textphoto.jpg");
outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CONSULT_DOC_CAMERA);
}
}
}).create().show();
}
};
[java]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ConsultDoctor.CONSULT_DOC_PICTURE) {
if(data == null){
return;
}
Uri uri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, proj, // Which
// columns
// to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
if (bmp != null)// 如果不釋放的話,不斷取圖片,將會內存不夠
bmp.recycle();
bmp = BitmapFactory.decodeFile(path);
iv.setImageBitmap(bmp);
} else if (requestCode == ConsultDoctor.CONSULT_DOC_CAMERA) {
bmp = BitmapFactory.decodeFile(outputFileUri.getPath());
iv.setImageBitmap(bmp);
} else {
Toast.makeText(getActivity(), "請重新選擇圖片", Toast.LENGTH_SHORT).show();
}
}
我的代碼是寫在Fragment裡面的。so... 你們懂的