我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:

[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];

在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。

public void DoSomething()
{
     //do something here
}

当前回答

类似的解决方案,但使用起来更干净

把这个函数写在类的外面

fun delay(duration: Long, `do`: () -> Unit) {

    Handler().postDelayed(`do`, duration)

}

用法:

delay(5000) {
    //Do your work here
}

其他回答

以下是我的最短解决方案:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms
    }
}, 100);

科特林

Handler(Looper.getMainLooper()).postDelayed({
    //Do something after 100ms
}, 100)

Java

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms
    }
}, 100);

要导入的类是android.os.handler。

下面是Kotlin的答案,你们这些懒惰的人:

Handler().postDelayed({
//doSomethingHere()
}, 1000)

对活动类的另一个响应(java8)。

//hide with delay
new Thread(() -> {
    try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
    this.runOnUiThread(() -> {
        myView.setVisibility(View.GONE);//this run on GUI
    });
}).start();

有很多方法可以做到这一点,但最好的是使用如下处理程序

long millisecDelay=3000

Handler().postDelayed({
  // do your work here
 },millisecDelay)