问题描述
我想做一个简单的游戏,用一个图像视图和两个按钮来猜测卡片是否是黑色的红色。
我想使用一个线程,在玩家按下按钮之前每隔0.1秒,卡片就在更换。
这是我到目前为止使用的:
Thread timer = new Thread() {
        public void run() {
            while (true) {
                try {
                    if(!isInterrupted())
                        sleep(100);
                    else
                        sleep(5000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(!isInterrupted()) {
                                if (iv_card_to_Guess.getDrawable() == null)
                                    iv_card_to_Guess.setImageBitmap(deck_card);
                                else
                                    iv_card_to_Guess.setImageDrawable(null);
                            }
                            else {
//here need to update imageview with the actual image of the card, not just the deck or null
// for example 5 of Hearts
                                loadBitmap(getResourceID("img_" + numbers.get(count).toString(), "drawable", getApplicationContext()), iv_card_to_Guess);
                            }
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
  
   
   
     当我按下按钮时,我调用timer.interrupt(); 
该应用程序更改实际卡的图像,但也需要0.1秒,而不是5秒,就像我想要的一样:)
请问我该怎么做?
1楼
     private Timer timer; 
      TimerTask task = new TimerTask() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
          insert the code you want to trigger here.
        }
    };
    timer = new Timer();
    int delay=5000;
    timer.schedule(task, delay); 
 
 2楼
 
     您正在执行的操作会带来一些不确定性。 
     我不确定确切的实现,但是如果isInterrupted()返回true并且您调用sleep(5000) ,则可能会立即抛出InterruptedException而不会进行任何睡眠。 
     此外,在清除中断状态之前,主线程中的Runnable可能会运行,以便您的卡看起来像预期的那样,只在您的while循环的下一次迭代(仅渗入0.1秒)时被删除。 
因此,相反,您最好使用Android动画来完成闪烁效果
if (iv_card_to_Guess.getDrawable() == null)
    iv_card_to_Guess.setImageBitmap(deck_card);
else
    iv_card_to_Guess.setImageDrawable(null);
 
   
     最好startAnimation()介绍两种方法startAnimation()和stopAnimation 。 
     您可以在Android上找到有关的指南。 
使用这些按钮,您可以停止动画,在单击按钮时,然后使用再次启动动画,使卡的曝光时间为5秒。
public void onClick(View v) {
    stopAnimation();
    loadBitmap(getResourceID("img_" + numbers.get(count).toString(), "drawable", getApplicationContext()), iv_card_to_Guess);
    iv_card_to_Guess.postDelayed(new Runnable() {
        startAnimation();
    }, 5000);
}