如何在 Android 中的 onActivityResult 方法中创建图像视图?

How to create image views inside onActivityResult method in Android?

我想在 onActivityResult 方法中动态创建图像视图。

如果我这样定义我的 ImageViewimageView = (ImageView) findViewById(R.id.image_view); 与此代码完美配合:

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

    if (requestCode == PICK_PHOTO && resultCode == RESULT_OK) {
        Uri uri = data.getData();

        StorageReference photoStorageReference = storageReference.child(uri.getLastPathSegment());
        photoStorageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUri = taskSnapshot.getDownloadUrl();
                Picasso.with(StorageActivity.this).load(downloadUri).fit().centerCrop().into(imageView);
            }
        });
    }
}

但是如果我像这样在 onActivityResult 方法中创建图像视图:

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

    if (requestCode == PICK_PHOTO && resultCode == RESULT_OK) {
        Uri uri = data.getData();

        StorageReference photoStorageReference = storageReference.child(uri.getLastPathSegment());
        photoStorageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUri = taskSnapshot.getDownloadUrl();
                ImageView imageView = new ImageView(getApplicationContext());
                linearLayout.addView(imageView);
                Picasso.with(StorageActivity.this).load(downloadUri).fit().centerCrop().into(imageView);
            }
        });
    }
}

图片浏览量未显示。我试图以编程方式在 onCreate 方法中创建那些图像视图,但同样的问题。什么都不显示。如果我创建按钮而不是 ImageView,按钮会正确显示。我的代码有什么问题?

提前致谢!

您忘记为新添加的视图指定 LayoutParameters。喜欢下面

imageView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));