gpt4 book ai didi

android - Runnable 未在 Android 上的 float 操作栏上运行

转载 作者:太空狗 更新时间:2023-10-29 13:51:50 26 4
gpt4 key购买 nike

我一直在尝试让 fab 旋转并更改其图标,但由于某些原因 Runnable 根本不起作用。

代码如下:

private val handler: Handler = Handler()
private var isRotate: Boolean = false
private val rotate: Animation = RotateAnimation(0.toFloat(),90.toFloat(),0.toFloat(),0.toFloat())

private val r: Runnable = Runnable {
fun run() {
if (isRotate) {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_camera, null))
isRotate = false
} else {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_gallery, null))
isRotate = true
}
}
}

override fun onCreate(savedInstanceState: Bundle?) {

...

rotate.duration = 1000
rotate.repeatCount = 0
rotate.repeatMode = Animation.REVERSE
rotate.fillAfter = true

fab2?.setOnClickListener { view ->
ObjectAnimator.ofFloat(view,"rotation",0.toFloat(),90.toFloat()).setDuration(800).start()
view.handler.postDelayed(r,400)
}
}

Button 旋转但图标没有改变,这意味着 OnClickListener 正在工作,但 Runnable 没有。

我怎样才能做到这一点?

最佳答案

您以错误的方式声明了 Runnable。您声明的 lambda 表达式实际上是 run() 函数,您在其中声明了另一个 run() 函数。

声明对象的正确方法应该是:

private val r: Runnable = object: Runnable {
override fun run() {
if (isRotate) {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_camera, null))
isRotate = false
} else {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_gallery, null))
isRotate = true
}
}
}

或者(lambda 表达式):

private val r: Runnable = Runnable {
if (isRotate) {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_camera, null))
isRotate = false
} else {
fab2.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_menu_gallery, null))
isRotate = true
}
}

关于android - Runnable 未在 Android 上的 float 操作栏上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45797406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com