Android Studio无法在图像视图中显示图像

时间:2019-02-06 17:07:40

标签: java android android-intent

//全局变量

 static final int CAMERA_REQUEST = 1;
ImageView imageview;
Bitmap bitmap;

//创建时:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

//获取参考

    imageview = findViewById(R.id.image_view);

// onclick侦听器和意图:

    Button take_photo_btn = findViewById(R.id.photo_btn);
    take_photo_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST);

        }
    });

//这是结果的活动:

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

    if (requestCode == CAMERA_REQUEST && requestCode == RESULT_OK) {
        Bundle extras = data.getExtras();
         bitmap = (Bitmap) extras.get("image");
            imageview.setImageBitmap(bitmap);
        }

    }
}

拍照后,我在图像视图中没看到它是什么问题?

3 个答案:

答案 0 :(得分:2)

如果您正在使用棉花糖,则必须在Android中使用Camera实现运行时权限。

更多详细信息,请点击此链接https://developer.android.com/training/permissions/requesting

答案 1 :(得分:1)

假设您已在清单中包含了摄像头权限:

<uses-permission android:name="android.permission.CAMERA" />

尝试检查用户是否已授予使用相机的权限:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)

然后这可以解决您在棉花糖中遇到的问题:

requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);

答案 2 :(得分:0)

好,我发现了问题

if (requestCode == CAMERA_REQUEST && requestCode == RESULT_OK

我需要这样做:

if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)