如何设置setOnClickListener的延迟?

时间:2017-04-13 10:16:11

标签: android delay

下面的代码是ImageButton在每次点击时更改其图像,我创建了一个循环来改变它的位置,但它改变得如此之快。所以我需要一个延迟函数,我已经尝试this solution但是没有为我工作。

  

它说“处理程序是抽象的,无法实例化”

代码:

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

5 个答案:

答案 0 :(得分:1)

使用handler.postDelay

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

其中1000表示1秒

答案 1 :(得分:0)

尝试此操作并将毫秒作为参数传递:

private void cmbId_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    UGrid.ItemsSource = new List<YourEntityType> { cmbId.SelectedItem as YourEntityType };
}

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

答案 2 :(得分:0)

  

我尝试过这个解决方案,但对我来说不起作用,它说“Handler   是抽象的,无法实例化“

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

您应该导入以下

  

导入android.os.Handler;

答案 3 :(得分:0)

您可以尝试使用此代码;

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

  // your code

 }
                }, 3000); // milisecond

答案 4 :(得分:0)

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


 }

您似乎导入了错误的Handler类

import java.util.logging.Handler;

将其更改为

import android.os.Handler;