2014-01-21 83 views
1

嘗試了很多方法,但沒有達到積極的結果。 在TableLayout具有ImageView的:從SD卡加載圖像到imageview不起作用

<TableLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/photo_layout_background" 
    android:stretchColumns="*" > 

    <TableRow 
     android:background="@color/photo_layoutrow_background" 
     android:layout_weight="1" 
     android:layout_marginBottom="4dp" 
     android:gravity="center" > 

    <ImageView 
     android:id="@+id/photo1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginRight="4dp" 
     android:src="@drawable/icon_photo" 
     android:background="@color/photo_background" 
     android:clickable="true" 
     android:onClick="addPhoto_Click"/> 

當您在ImageView提供的標準程序點擊獲得的圖片和文件被保存在SD卡上:

public void addPhoto_Click(View v){ 
    select_add_photo_id = v.getId(); 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, generateFilePhotoUri()); 
    startActivityForResult(takePictureIntent, CAMERA_RESULT); 
} 

@SuppressLint("SimpleDateFormat") 
private Uri generateFilePhotoUri() { 
    File file = null; 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    file = new File(MEDIA_PATH + String.valueOf(id) + File.separator + timeStamp + ".jpg"); 
    select_add_photo_file = file.getAbsolutePath(); 
    return Uri.fromFile(file); 
} 

照片被保存通常存儲在變量select_add_photo_id id ImageView上點擊了select_add_photo_file變量,保存文件照片的完整路徑。

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAMERA_RESULT) { 
     if (resultCode == RESULT_OK){ 
      ImageView imgView = (ImageView) findViewById(select_add_photo_id); 
      imgView.setImageDrawable(Drawable.createFromPath(select_add_photo_file)); 

     } 

    } 
} 

但是,當文件只有ImageView ImageView帶背景和增加尺寸。攝影未加載。沒有錯誤。

仍然設置照片?

回答

1

取後一個電話,在onActivityResult,data.getData可以爲空,在這種情況下,嘗試data.getExtras()

Bitmap photo = null; 
Uri photoUri = data.getData(); 
String filePath = ""; 
if (photoUri != null) { 
    //mFilePath = getRealPathFromURI(photoUri); 
    filePath = getRealPathFromURI(photoUri); 
    photo = BitmapFactory.decodeFile(photoUri.getPath()); 
} 
if (photo == null) { 
    Bundle extra = data.getExtras(); 
    if (extra != null) { 
     photo = (Bitmap)extra.get("data"); 
... 
+0

錯誤上烏里photoUri = data.getData(); – SmallSani

+0

@SmallSani更多細節?我在我的一個項目中使用了這個代碼,它工作。 – jiashie

+0

對不起,程序邏輯中有錯誤。是的,你的代碼有效。謝謝! – SmallSani