单击按钮后如何延迟2秒?

时间:2017-12-01 18:08:16

标签: android database android-studio-3.0

我的代码正在使用' case&break'例子

                    case R.id.student:

                    showMessage("Student");

                    Intent std = new Intent(Home.this, student.class);

                    startActivity(std);

                    break;

5 个答案:

答案 0 :(得分:1)

试试这个

switch (menuButton.getId()) {
        case R.id.student:
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showMessage("Student");
                    Intent std = new Intent(Home.this, student.class);
                    startActivity(std);
                }
            }, 2000);
            break;
    }

答案 1 :(得分:0)

使用Runnable:

Handler handler = new Handler();
final Runnable r = new Runnable() {
    public void run() {
        handler.postDelayed(this, 1000);
        // TO DO
    }
};

使用处理程序:

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TO DO
            }
        }, 1000);

在你的情况下就像:

        switch (menuButton.getId()) {
            case R.id.student:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        showMessage("Student");
                        Intent std = new Intent(Home.this, student.class);
                        startActivity(std);
                    }
                }, 1000);

                break;

        }

答案 2 :(得分:0)

     public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.btn_cherry) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // do what you want after 1000 miliseconds
                }
            }, 1000);
        }

答案 3 :(得分:0)

可以使用倒数计时器,它位于对象类中,如下所示

 new CountDownTimer(2000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

这将启动计时器2秒钟,您可以在ontick和onfinish块中处理所需的事件。

你可以进一步参考android官方文档

countdown timer

答案 4 :(得分:0)

假设您已经在第二个x(startTime)点击了一个按钮,现在您需要在x + 2秒内启用按钮执行的操作,然后再次单击x + 2 + 2,为此

long startTime = System.currentTimeMillis();
long difference = System.currentTimeMillis() - startTime;
int seconds=difference/1000; //(this will change milisecond to second 
required value)
if(seconds>2){
//do task
}else{
return; //do not do task or return 
}
// this can be done for one or more than one switches at same time to avaiod multiple click of a button or clicking multiple button at short interval of time

prevent rapid click