使用 Kotlin 实现 Picasso 回调函数

11

我正在使用Kotlin制作Android应用程序,并需要使用Picasso下载图像。我看到下面的Java代码用于为图像设置动画,但我无法将其转换为Kotlin,因为我不知道如何在“into”函数中设置Callback。

Picasso.with(MainActivity.this)
       .load(imageUrl)
       .into(imageView, new com.squareup.picasso.Callback() {
                    @Override
                    public void onSuccess() {
                        //set animations here

                    }

                    @Override
                    public void onError() {
                        //do smth when there is picture loading error
                    }
                });

有人能帮我吗?

我的实际代码:

Picasso.with(context)
       .load(url)
       .into(imageDiapo, com.squareup.picasso.Callback)

4
在 Kotlin 中这看起来像是 object: Callback{} - Stanislav Bondar
在我的情况下,我使用的是CustomeImageView,我已经将其替换为ImageView并且正常工作。 - varotariya vajsi
3个回答

23
Picasso.with(MainActivity::this)
       .load(imageUrl)
       .into(imageView, object: com.squareup.picasso.Callback {
                    override fun onSuccess() {
                        //set animations here

                    }

                    override fun onError(e: java.lang.Exception?) {
                        //do smth when there is picture loading error
                    }
                })

16

在最新版本中,onError 接收一个 Exception 作为参数,并使用 get() 而不是 with()

  Picasso.get()
  .load(imageUrl)
  .into(imageView, object :Callback{
   override fun onSuccess() {
   Log.d(TAG, "success")
   }

   override fun onError(e: Exception?) {
   Log.d(TAG, "error")
   }
   })

在之前的版本中

   Picasso.with(MainActivity::this)
   .load(imageUrl)
   .into(imageView, object: Callback {
                override fun onSuccess() {
                   Log.d(TAG, "success")
                }

                override fun onError() {
                  Log.d(TAG, "error")
                }
            })

1
谢谢,我只是在寻找这个。 - Vinil Prabhu

1

你好,这里是 Picasso 提供的一些不同方式:

Picasso.with(context).load(path).into(imageView);

2.在我们的utils包内创建一个新文件,命名为picasso.kt,并填充以下简单代码:

 public val Context.picasso: Picasso
    get() = Picasso.with(this)

3. 尽管这对应于接收器对象,我们可以在任何上下文中调用以下代码:

picasso.load(path).into(imageView)
  1. We can go further and extend ImageView class like:

    public fun ImageView.load(path: String, request: (RequestCreator) -> RequestCreator) {
    request(getContext().picasso.load(path)).into(this)    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接