Search code examples
androiddelay

How to set a delay for setOnClickListener?


The below code is for ImageButton to change its image on every click. I have created a loop to change its position, but it changed so fast.

So I need a delay function. I have tried this solution, but it did not work for me.

It says "Handler is abstract and cannot be instantiated"

The code:

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);
}

Solution

  • Use handler.postDelay

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

    where 1000 means 1 second