2012-03-09 20 views
10

Tôi lấy Uri của một hình ảnh từ bộ sưu tập sử dụngUri trở lại sau ACTION_GET_CONTENT từ gallery không hoạt động trong setImageURI() của ImageView

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

và cố gắng để hiển thị các hình ảnh bằng cách

imageView.setImageURI(uri); 

đây , uri là Uri của hình ảnh nhận được trong onActivityResult bởi intent.getData().

nhưng không có hình ảnh nào đang được hiển thị. Ngoài ra, đối với

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

tệp.exists() đang trả về false.

+0

là bạn kiểm tra giá trị uri .. đăng nhập và kiểm tra .. dán uri ở đây – Ronnie

Trả lời

22

Vấn đề là bạn nhận được Uri nhưng từ uri đó bạn phải tạo Bitmap để hiển thị trong Hình ảnh của bạn. Có nhiều cơ chế khác nhau để làm cùng một trong số đó là mã này.

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

làm việc của nó cho tôi .. cảm ơn :) –

0

Launch Thư viện ảnh Chooser

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 là mã yêu cầu định nghĩa là một biến ví dụ.

private int PICK_IMAGE_REQUEST = 1; 

hiển thị lên các hình ảnh được chọn trong Hoạt động/Fragment

@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(); 
     } 
    } 
} 

bố trí của bạn sẽ cần phải có một ImageView như thế này:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView" /> 
Các vấn đề liên quan