【问题标题】:Convert indefinitely running Runnable from java to kotlin将无限期运行的 Runnable 从 java 转换为 kotlin
【发布时间】:2017-12-01 01:13:37
【问题描述】:

我在java中有一些这样的代码来监控某个文件:

private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};

这是我的 kotlin 代码:

private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}

我不明白我应该将什么 Runnable 传递给 mHandler.postDelayed。什么是正确的解决方案?另一个有趣的事情是,当我输入这段代码时,kotlin 到 java 的转换器会冻结。

【问题讨论】:

标签: java android kotlin


【解决方案1】:

Lambda 表达式没有this,但对象表达式(匿名类)有。

object : Runnable {
    override fun run() {
        handler.postDelayed(this, 1000)
    }
}

【讨论】:

    【解决方案2】:

    稍微不同的方法,可能更易读

    val timer = Timer()
    val monitor = object : TimerTask() {
        override fun run() {
            // whatever you need to do every second
        }
    }
    
    timer.schedule(monitor, 1000, 1000)
    

    发件人:Repeat an action every 2 seconds in java

    【讨论】:

      【解决方案3】:

      Lambda 表达式没有 this,但对象表达式(匿名类)有。那么更正后的代码是:

      private val mHandler = Handler()
      val monitor: Runnable = object : Runnable{
       override fun run() {
                         //any action
                      }
                      //runnable
      
                  }
      
       mHandler.postDelayed(monitor, 1000)
      

      【讨论】:

        【解决方案4】:

        runnable display Toast Message "Hello World per 4 seconds

        //在一个类主Activity里面

            val handler: Handler = Handler()
            val run = object : Runnable {
               override fun run() {
                   val message: String = "Hello World" // your message
                   handler.postDelayed(this, 4000)// 4 seconds
                   Toast.makeText(this@MainActivity,message,Toast.LENGTH_SHORT).show() // toast method
               }
        
           }
            handler.post(run)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-12-02
          • 2021-07-24
          • 2018-11-26
          • 2015-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多