Search code examples
androidfresco

How to set LinearLayout background image with Fresco in code


Earlier, I thought that Fresco can be used as a complete replacement of Picasso.

For example, I can use Picasso to load a Bitmap and set it on any view using solution as suggested on this SO answer.

Is this supported with Fresco?

To be more specific with my question, is it possible to set a loaded image using Fresco on any View, without having to create a custom View?


Solution

  • Sure its possible. Use next code:

    Uri imageUri = com.facebook.common.util.UriUtil.getUriForResourceId(imgResId);
    // or if you use link: 
    // Uri imageUri = Uri.parse(webLinkToTheImage);
    
    ImageRequestBuilder builder = ImageRequestBuilder
                .newBuilderWithSource(imageUri)
                .setRequestPriority(Priority.HIGH)
                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH);
    
        final DataSource<CloseableReference<CloseableImage>> dataSource =
                Fresco.getImagePipeline().fetchDecodedImage(builder.build(), imageUri);
    
        try {
            dataSource.subscribe(new BaseBitmapDataSubscriber() {
                @Override
                public void onNewResultImpl(@Nullable Bitmap bitmap) {
                    if (null != bitmap) {
                        //TODO use bitmap
                    }
                }
    
                @Override
                public void onFailureImpl(DataSource dataSource) {
                    if (dataSource != null) {
                        dataSource.close();
                    }
                }
            }, new MainThreadExecutor());
        } finally {
            if (dataSource != null) {
                dataSource.close();
            }
        }
    
    
    public class MainThreadExecutor implements Executor {
        private final Handler handler = new Handler(Looper.getMainLooper());
    
        @Override
        public void execute(@NonNull Runnable r) {
            handler.post(r);
        }
    }