Android 选择图片 相册选择 马上拍照
jopen
11年前
public class MainActivity extends Activity implements OnClickListener { private ImageView iv; private int SELECT_PICTURE = 1; // 从图库中选择图片 private int SELECT_CAMER = 2; // 用相机拍摄照片 private Bitmap bmp; @Override protected 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); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.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 block e.printStackTrace(); } iv.setImageURI(uri); } else { Toast.makeText(MainActivity.this, "选择图片失败,请重新选择", Toast.LENGTH_SHORT) .show(); } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (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() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (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() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }).create(); dialog.show(); } }