如何为 setOnClickListener 设置延迟?

How to set a delay for setOnClickListener?

以下代码用于 ImageButton 在每次点击时更改其图像。我已经创建了一个循环来改变它的位置,但它改变得太快了。

所以我需要一个延时功能。我试过 this solution,但它对我不起作用。

It says "Handler is abstract and cannot be instantiated"

代码:

public void ShapeSelectingInGame() {

    ShapeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShapeButton = (ImageButton) v;
            selectShape = rand.nextInt(4);
            ShapeSaying = rand.nextInt(8);
            ColorOfShape = rand.nextInt(10);
            shapeID = "shape_" + selectShape + ShapeSaying + ColorOfShape;
            resID = getResources().getIdentifier(shapeID, "drawable", "com.example.asgames.hitit");
            ShapeButton.setImageResource(resID);
            HitTypeString.setVisibility (View.INVISIBLE);
        }
    });

    for (int i = 10; i < 10000; i += 100)
    {
        ShapeButton.setX(i);
    }
    ShapeButton.setVisibility(View.VISIBLE);
}

试试这个并传递毫秒作为参数:

wait(20000);

20000 表示您正在等待 20 秒,其中 20000 是毫秒。

I have tried this solution but did not work for me it says "Handler is abstract and cannot be instantiated"

导入了错误的处理程序,即ava.util.logging.Handler

您应该导入以下内容

import android.os.Handler;

使用handler.postDelay

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
    // your code here
}
}, 1000);

其中 1000 表示 1 秒

你可以试试这个代码;

  new Handler().postDelayed(
                new Runnable() {
                    public void run() {

  // your code

 }
                }, 3000); // milisecond
   private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            ShapeButton = (ImageButton) v;
            selectShape = rand.nextInt(4);
            ShapeSaying = rand.nextInt(8);
            ColorOfShape = rand.nextInt(10);
            shapeID = "shape_" + selectShape + ShapeSaying + ColorOfShape;
            resID = getResources().getIdentifier(shapeID, "drawable", "com.example.asgames.hitit");
            ShapeButton.setImageResource(resID);
            HitTypeString.setVisibility (View.INVISIBLE);
        }
    };
    private static final int DELAY = 3000;
    public void ShapeSelectingInGame() {
        ShapeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.postDelayed(mRunnable, DELAY);
            }
        });

        for (int i=10; i<10000;i+=100)
        {
            ShapeButton.setX(i);
        }
        ShapeButton.setVisibility(View.VISIBLE);


 }

看来你导入了错误的Handlerclass

import java.util.logging.Handler;

改为

import android.os.Handler;