如何修复此代码中的弃用警告?或者,还有其他的选择吗?

Handler().postDelayed({
    context?.let {
        //code
    }
}, 3000)

当前回答

如果你想避免在Kotlin (?或者!!)你可以使用loop . getmainlooper()如果你的Handler正在处理一些UI相关的事情,像这样:

Handler(Looper.getMainLooper()).postDelayed({
   Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)

注意:如果使用fragment,请使用requireContext()而不是this@MainActivity。

其他回答

import android.os.Looper
import android.os.Handler

inline fun delay(delay: Long, crossinline completion: () -> Unit) {
    Handler(Looper.getMainLooper()).postDelayed({
        completion()
    }, delay)
}

例子:

delay(1000) {
    view.refreshButton.visibility = View.GONE
}

在Handler构造函数中提供一个循环器

Handler(Looper.getMainLooper())

只有无参数的构造函数已弃用,现在最好通过loop . getmainlooper()方法在构造函数中指定循环器。

用于Java

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // Your Code
    }
}, 3000);

将它用于Kotlin

Handler(Looper.getMainLooper()).postDelayed({
    // Your Code
}, 3000)

来源:developer.android.com

考虑使用协程

scope.launch {
    delay(3000L)
    // do stuff
}

如果你想避免在Kotlin (?或者!!)你可以使用loop . getmainlooper()如果你的Handler正在处理一些UI相关的事情,像这样:

Handler(Looper.getMainLooper()).postDelayed({
   Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)

注意:如果使用fragment,请使用requireContext()而不是this@MainActivity。