我在监视某个文件的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转换器会冻结。
答案 0 :(得分:20)
Lambda表达式没有this
,但是对象表达式(匿名类)没有。
object : Runnable {
override fun run() {
handler.postDelayed(this, 1000)
}
}
答案 1 :(得分:5)
稍微不同的方法可能更具可读性
val timer = Timer()
val monitor = object : TimerTask() {
override fun run() {
// whatever you need to do every second
}
}
timer.schedule(monitor, 1000, 1000)
答案 2 :(得分:1)
Lambda表达式没有 this ,但是对象表达式(匿名类)具有。那么正确的代码将是:
const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
const container = document.getElementById('container');
let div = document.createElement('div');
div.classList.add('box');
container.appendChild(div);
}
function fillBox(evt){
evt.preventDefault(); // tell the browser we handle that event
this.classList.add('filled');
}
function clearGrid(){
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.classList.remove('filled'));
}
function startDrawing(evt){
evt.preventDefault(); // tell the browser we handle that event
// console.log("start drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}
function stopDrawing(evt){
evt.preventDefault(); // tell the browser we handle that event
// console.log("stop drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}
const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);
const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;
答案 3 :(得分:1)
runnable 显示 Toast Message "Hello World 每 4 秒
//在一个类的主要活动中
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)
}