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

时间:2017-01-09 22:06:11

标签: android imageview onactivityresult

我想在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按钮,则按钮会正确显示。我的代码出了什么问题?

提前致谢!

1 个答案:

答案 0 :(得分:0)

您忘记为新添加的视图指定LayoutParameters。如下所示

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