首页 > 解决方案 > 毕加索在 android 中使用匹配父项获取的最佳实践

问题描述

我正在使用 Picasso 下载图片并在 RecyclerView 中显示它们。我试图防止在滚动 RecyclerView 和 Picasso 正在下载新图片时发生的小延迟,所以我正在使用 fetch。当我为图片使用精确尺寸时,它运行良好,但现在我在我的 xml 中使用“匹配父级”(在所有设备上工作),从那时起有一个延迟,当我向后滚动时第四,它不记得图片(延迟已经看过的图片)。我尝试了 fit() 和 centerCrop() 但它很慢,所以这是我目前解决问题的尝试:

在适配器中(这只运行一次)我设置了一个监听器来获取 ImageViews 的确切大小

private void preloadImage(final View picture) {
    ViewTreeObserver observer = picture.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            PictureUtil.fetchImage(picture.getHeight(), picture.getWidth());
            ViewTreeObserver mObserver = picture.getViewTreeObserver();
            mObserver.removeOnGlobalLayoutListener(this);
        }
    });
}

在 PictureUtil 中,我获取所有图片:

   public static void fetchImage(int height, int width) {
    if (height > 0 && width > 0) {
        for (House house : Houses.houseList) {
            Picasso.get().load(getFrontPicturePath(house.id))
                    .resize(width, height)
                    .centerCrop()
                    .fetch();
        }
    }
}

在适配器中,这就是我加载它们的方式:

Picasso.get()
            .load(PictureUtil.getFrontPicturePath(houseId))
            .error(PictureUtil.getPlaceholderPath(context))
            .fit()
            .centerCrop()
            .into(view);

这是xml中的imageview:

        <ImageView
            android:id="@+id/house_row_picture"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:src="@drawable/img_small" />

因此,我再次遇到图像延迟的问题(不像我有固定尺寸时),当我在 Recyclerview 中滚动时,图像消失并再次加载。我究竟做错了什么?对此有最佳做法吗?

提前致谢

标签: androidandroid-recyclerviewpicassoprefetch

解决方案


推荐阅读