将图像从SD卡加载到imageview无法正常工作

时间:2014-01-21 05:22:33

标签: android imageview sd-card

尝试了很多方法,但没有达到积极的结果。 在TableLayout中有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 个答案:

答案 0 :(得分:1)

拿了手机之后,在onActivityResult中,data.getData可能为null,在这种情况下,请尝试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");
...