Runnable不能在Android上的浮动操作栏上运行
我一直在试图让晶圆厂旋转并改变它的图标,但由于某种原因, 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) } }
按钮旋转,但图标不会改变意味着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 } }