安卓开发调用系统图片库

在android中,如何从图库gallary中挑选图片呢,其实很简单,步骤如下


1) 设计一个imageview,用来显示图库选出来的图片

  
Java代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent"
  6.     >
  7.         <ImageView
  8.                         android:id="@+id/imgView"
  9.                         android:layout_width="fill_parent"
  10.                         android:layout_weight="1" android:layout_height="wrap_content"></ImageView>
  11.         <Button 
  12.                         android:layout_height="wrap_content" 
  13.                         android:text="Load Picture" 
  14.                         android:layout_width="wrap_content" 
  15.                         android:id="@+id/buttonLoadPicture" 
  16.                         android:layout_weight="0" 
  17.                         android:layout_gravity="center"></Button>
  18. </LinearLayout>
复制代码
2) 学习如何在按键中调出gallary,其实也就是intent了,如下

   Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE);



3) 然后在onActivityResult中对调出图库后,选定好的图片,我们要重新显示在页面的imageview中,因此代码如下:

Java代码
  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  2.             super.onActivityResult(requestCode, resultCode, data);
  3.             
  4.                 if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
  5.                         Uri selectedImage = data.getData();
  6.                         String[] filePathColumn = { MediaStore.Images.Media.DATA };
  7.                         Cursor cursor = getContentResolver().query(selectedImage,
  8.                                         filePathColumn, null, null, null);
  9.                         cursor.moveToFirst();
  10.                         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  11.                         String picturePath = cursor.getString(columnIndex);
  12.                         cursor.close();
  13.                         
  14.                         ImageView imageView = (ImageView) findViewById(R.id.imgView);
  15.                         imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
  16.                 
  17.                 }
复制代码
其中就是Uri selectedImage = data.getData();获得了图库中的图片所有数据了。

猜你喜欢

转载自546945802-qq-com.iteye.com/blog/1846783