Runnable没有在Android上的浮动操作栏上运行

时间:2017-08-21 12:40:27

标签: android kotlin

我一直试图让工厂旋转并更改其图标但由于某种原因,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不起作用。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

您正以错误的方式声明setA 0 - 0 setB 100 - 300 setC 0 - 0 setD 500 - 1000 setE 0 - 0 setF 0 - 0 setG 0 - 0 。您声明的lambda表达式实际上是Runnable函数,您在其中声明了另一个run()函数。

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

run()

或(lambda表达):

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
        }
    }
}