【问题标题】:Dynamically setting ImageView.setImageUri not displaying image动态设置 ImageView.setImageUri 不显示图像
【发布时间】:2018-05-07 18:39:13
【问题描述】:

我有以下场景:

我正在动态地将图像 URI 分配给 ImageView,然后将此 ImageView 动态添加到 Horizo​​ntalView。

问题是,我没有看到这些图像加载到 ImageView 中,在 Horizo​​ntalView 中。

这是我的代码:

<HorizontalScrollView
                android:layout_width="wrap_content"
                android:layout_height="100dp">
                <LinearLayout
                    android:id="@+id/imageDisplayer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                </LinearLayout>
            </HorizontalScrollView>

这是我加载图片的代码:

public void LoadImages(ArrayList<PhotoPath> photos){
        LinearLayout layout = (LinearLayout)findViewById(R.id.imageDisplayer);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        if (photos != null) {
            for (PhotoPath photo : photos) {
                Uri photoUri = Uri.parse(photo.getPhotoPath());

                params.setMargins(10, 10, 10, 10);
                params.gravity = Gravity.NO_GRAVITY;

                ImageView imageView = new ImageView(this);
                imageView.setImageURI(photoUri);
                imageView.setLayoutParams(params);

                layout.addView(imageView);
            }
        }
    }

这是我的 URI 示例:

content://com.android.providers.media.documents/document/image%3A48

我做错了什么?

【问题讨论】:

  • 使用 glide 或 Picasso 加载图片!

标签: java android android-imageview


【解决方案1】:

setImageURI(Uri uri) 在 UI 线程上执行 Bitmap 读取和解码。所以这可能会导致 MainThread 延迟,因为图像大小可能会发生变化,并且加载需要时间。并且由于它在主线程上,所以它可能会导致延迟问题。

来自文档

setImageURI(Uri uri) 在 UI 线程上进行位图读取和解码,这可能会导致延迟打嗝。如果这是一个问题,请考虑使用 setImageDrawable(Drawable) 或 setImageBitmap(android.graphics.Bitmap) 和 BitmapFactory。

有效的解决方案是使用优化的 ImageLoader 库。您可以使用Glide,因为它被广泛推荐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多