2017-04-13 53 views
1

下面的代码是为ImageButton在每次点击时更改其图像,我创建了一个循环来改变它的位置,但它改变得非常快。所以我需要一个延迟功能,我试过this solution,但没有为我工作。如何为setOnClickListener设置延迟?

它说: “处理程序是抽象的,不能被实例化”

代码:

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

看到我的回答你输入错误处理程序 –

回答

1

使用handler.postDelay

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

,其中1000是指1秒

+0

它说“处理程序是抽象的,不能实例化” –

+0

不应该来,请确保你正在导入android.os。处理程序; – Anmol

+0

它的工作,谢谢你:D –

0

试试这个,通过毫秒为参数:

wait(20000); 

20000手段你正在等待20秒,其中20000是毫秒。

+0

但是,这不是一个好方法因为它冻结了用户界面。 –

+0

它说“未处理的excation:java.lang.InterruptedExcpetion” –

+0

你没有在正确的地方使用它 –

0

我已经试过这个解决方案,但我没有工作,它说:“处理程序 是抽象的,不能被实例化”

进口错误处理程序这是ava.util.logging.Handler

你应该输入以下内容

import android.os.Handler;

0

你可以试试这个代码;

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

    // your code 

} 
       }, 3000); // milisecond 
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); 


} 

看来你已经导入了错误的处理程序类

import java.util.logging.Handler; 

将其更改为

import android.os.Handler; 
+0

我纠正了,但对象v不再声明和图像按钮从未出现 –