Android - 在ImageView中显示图像

时间:2014-12-30 16:40:52

标签: android image

我是Android新手,我正在尝试显示相机拍摄的图像。我使用ImageView来执行此操作。但是当我运行我的应用程序时,ImageView元素才会显示。以下是activity_main.xml的摘录:

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

以下Main_Activity.java中的代码更改了src属性:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ImageView img = (ImageView) findViewById(R.id.image_front);

        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile(1);
            } catch (IOException e) {
                // Error occurred when creating a file
                System.out.println(e.getLocalizedMessage());
            }
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                img.setImageURI(Uri.fromFile(photoFile));
            }
        }

我可能做错了什么,所以有人能指出我的错误吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

当您&#34;为结果&#34;启动活动时,您的当前活动将暂停,并启动新的活动(由意图引用)。一旦完成它必须执行的任何任务,您的先前活动将恢复,并且&#34; onActivityResult&#34;方法被称为。

在该方法中,您需要加载图片并将其设置为图片视图:(将photoFile设置为活动的实例变量)

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        photoFile = null;
        try {
            photoFile = createImageFile(1);
        } catch (IOException e) {
            // Error occurred when creating a file
            System.out.println(e.getLocalizedMessage());
        }
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

然后实现onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    switch(requestCode)
    {
    case REQUEST_IMAGE_CAPTURE:
        if(resultCode == RESULT_OK)
        {
            ImageView img = (ImageView) findViewById(R.id.image_front);
            img.setImageURI(Uri.fromFile(photoFile));
        }
        break;
    }
}

答案 1 :(得分:0)

从相机回拨你需要的

之类的东西
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_IMAGE_CAPTURE:
if(resultCode == RESULT_OK) {
img.setImageURI(Uri.fromFile(photoFile));
}
break;
}
}