按下后重新加载图像

问题描述

我有两个活动,A 和 B。当用户按下 A 中的按钮时,B 启动并使用 Picasso 加载图像。

Example A to B

用户按下返回然后再次按下 A 中的按钮时,B 显示相同的图像。

我希望重新加载 B 中的图像以显示不同的图像。

A to B image reloaded after pressing back

我如何重新加载它?我正在考虑将 B 中的图像加载代码onCreate() 移动到 onRestart()onResume()。这是正确的想法吗?

按钮:

val goButton = findViewById<Button>(R.id.btn_go)
        goButton.setonClickListener {
            val intent = Intent(this,WritingActivity::class.java)
            startActivity(intent) 
        }

加载图片

private const val RAND_IMAGE_URL:String = "https://images.unsplash.com/photo-1617386564901-be7cfcaa4c60?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixlib=rb-1.2.1&q=80&w=800"


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_writing)

        // Load the random image
        val image = findViewById<ImageView>(R.id.iv_image)
        Picasso.get().load(RAND_IMAGE_URL)
                        .error(R.drawable.ic_error_outline_72)
                        .into(image,object : Callback {
                            override fun onSuccess() {
                                // successfully loaded,start countdown timer
                                startTimer()
                                //  hide progress bar
                                progressBar.visibility = View.GONE
                            }

                            override fun onError(e: Exception?) {
                                // display error message
                                Toast.makeText(this@WritingActivity,R.string.error_loading_image,Toast.LENGTH_LONG).show()
                                Log.e(TAG,"error loading image",e)
                                //  hide progress bar
                                progressBar.visibility = View.GONE
                            }

                        })
    }

解决方法

我认为您不需要在 onCreate 函数中移动代码。 当您按下返回按钮时,B 活动生命周期已经处于停止状态。 这就是为什么当你再次按下 A 中的按钮时,它会再次调用 onCreate 函数。 我认为需要在每个生命周期中生成随机图像 url。 谢谢

,

仅将毕加索代码移入 onResume()

,

当您通过浏览器访问此 URL 时,它会进行一些处理并每次向您显示随机图像。

但在 Picasso 的情况下,Picasso 在从服务器获取它之前首先根据相同的 URL 检查其缓存。由于 URL 是不变的,它会向您显示首先获取的相同图像。

在这种情况下,您可以清除 Picasso 的缓存或请求 Picasso 为该 URL 加载新图像。

Picasso.with(this)
   .load(URL).skipMemoryCache().into(YOUR_IMAGE_VIEW);