public class MainActivity extends Activity implements OnClickListener {private ImageView iv;private int SELECT_PICTURE = 1; // 從圖庫中選擇圖片private int SELECT_CAMER = 2; // 用相機拍攝照片private Bitmap bmp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private void init() {iv = (ImageView) findViewById(R.id.imageView1);iv.setOnClickListener(this);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) {Uri uri = data.getData();ContentResolver cr = this.getContentResolver();try {if (bmp != null) {bmp.recycle();bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}iv.setImageURI(uri);} else {Toast.makeText(MainActivity.this, "選擇圖片失敗,請重新選擇", Toast.LENGTH_SHORT).show();}}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.imageView1:showChoosePhotoDialog();break;default:break;}}private void showChoosePhotoDialog() {CharSequence[] items = { "相簿", "相機" };AlertDialog dialog = new AlertDialog.Builder(this).setTitle("選擇圖片來源").setItems(items, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubif (which == SELECT_PICTURE) {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(intent, SELECT_CAMER);} else {Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");startActivityForResult(intent, SELECT_PICTURE);}}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog.cancel();}}).create();dialog.show();}}