2017-04-13 54 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不再聲明和圖像按鈕從未出現 –