androidfacebookfresco

Facebook Fresco using wrap_content


I got a bunch of drawables that I want to load using fresco, I want to use wrap_content size for those images, how can I do it in xml with fresco? Or if xml is not possible how do you do it in code?

<com.facebook.drawee.view.SimpleDraweeView
          android:id="@+id/myImage"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          fresco:placeholderImage="@mipmap/myImage"/>

The above code is not working unless I set a fixed size.


Solution

  • I am part of the Fresco team and I was the one who made the design decision to not support wrap-content. The rationale is explained in the documentation. But in short, the problem is that you can't guarantee that the image will be available immediately (you may need to fetch it first) and that means that the view size would have to change once the image arrives. This is in most cases not desirable and you should probably rethink your UI.

    Anyways, if you really really need/want to do that, you can do it like this:

    void updateViewSize(@Nullable ImageInfo imageInfo) {
      if (imageInfo != null) {
        draweeView.getLayoutParams().width = imageInfo.getWidth();
        draweeView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
        draweeView.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
      }
    }
    
    ControllerListener listener = new BaseControllerListener {
        @Override
        public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
          updateViewSize(imageInfo);
        }
    
        @Override
        public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable animatable) {
          updateViewSize(imageInfo);
        }
      };
    
    DraweeController controller = draweeControllerBuilder
      .setUri(uri)
      .setControllerListener(listener)
      .build();
    draweeView.setController(controller);
    

    I wrote this code from the top of my head, I haven't actually tested it. But the idea should be clear, and it should work with minor adjustments.