Synchronous image loading on a background thread with Picasso - without .get()

后端 未结 2 608
有刺的猬
有刺的猬 2021-01-15 08:16

I have a custom viewgroup (that contains Picasso-loaded images) that can be reused in two places:

  1. Displayed to the user in the application (on the UI thread)
相关标签:
2条回答
  • 2021-01-15 08:41

    Here is my solution:

    /**
     * Loads the request into an imageview.
     * If called from a background thread, the request will be performed synchronously.
     * @param requestCreator A request creator
     * @param imageView The target imageview
     * @param callback a Picasso callback
     */
    public static void into(RequestCreator requestCreator, ImageView imageView, Callback callback) {
      boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
      if (mainThread) {
        requestCreator.into(imageView, callback);
      } else {
        try {
          Bitmap bitmap = requestCreator.get();
          imageView.setImageBitmap(bitmap);
          if (callback != null) {
            callback.onSuccess();
          }
        } catch (IOException e) {
          if (callback != null) {
            callback.onError();
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-15 08:41

    Perfect answer by Jacob Tabak

    Here is small addition that handles the case if you load image into Target. I haven't found a way to get the origin of image to pass appropriate LoadedFrom argument.

     public static void into(RequestCreator requestCreator, Drawable placeHolder, Drawable errorDrawable, Target target) {
            boolean mainThread = Looper.myLooper() == Looper.getMainLooper();
            if (mainThread) {
                requestCreator.into(target);
            } else {
                try {
                    target.onBitmapFailed(placeHolder);
                    Bitmap bitmap = requestCreator.get();
                    target.onBitmapLoaded(bitmap, Picasso.LoadedFrom.MEMORY);
                } catch (IOException e) {
                    target.onBitmapFailed(errorDrawable);
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题