2012-03-09 23 views
10

我從庫取出一個圖像的Uri的使用烏里之後,從畫廊ACTION_GET_CONTENT不setImageURI ImageView的

Intent intent = new Intent(); 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), requestCode); 

工作(),並試圖通過

imageView.setImageURI(uri); 

這裏顯示的圖像返回,uri是通過intent.getData()在onActivityResult中接收的圖像的Uri。

但沒有圖像顯示。另外,對於

File file=new File(uri.getPath()); 

file.exists()返回false。

+0

你是否檢查uri值..日誌和檢查..粘貼在這裏的uri – Ronnie 2012-04-22 13:13:37

回答

22

問題是,你得到的Uri,但從該URI你必須創建位圖顯示在你的ImageView。這個代碼有各種機制可以做同樣的工作。

Intent intent = new Intent(); 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), 1); 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if(resultCode==RESULT_CANCELED) 
    { 
     // action cancelled 
    } 
    if(resultCode==RESULT_OK) 
    { 
     Uri selectedimg = data.getData(); 
     imageView.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg)); 
    } 
} 
+0

其工作對我..謝謝:) – 2016-12-13 13:15:38

0

啓動所述圖庫選配

Intent intent = new Intent(); 
// Show only images, no videos or anything else 
intent.setType("image/*"); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
// Always show the chooser (if there are multiple options available) 
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); 

PICK_IMAGE_REQUEST是定義爲一個實例變量的請求代碼。

private int PICK_IMAGE_REQUEST = 1; 

顯示在活動所選圖像/片段

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { 

     Uri uri = data.getData(); 

     try { 
      Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); 
      // Log.d(TAG, String.valueOf(bitmap)); 

      ImageView imageView = (ImageView) findViewById(R.id.imageView); 
      imageView.setImageBitmap(bitmap); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

您的佈局需要有這樣一個ImageView的:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView" />