0

我有几个按钮,我想随机出现,然后在几秒钟后消失。我还希望它们在可见时可以点击,如果这有任何改变的话。

这是我所拥有的:

public void fight() throws InterruptedException
{
    Random g = new Random();
    int move;
    for(int i = 0; i <= 3; i++)
    {
        move = g.nextInt(8);
        buttons[move].setVisibility(View.VISIBLE);
        buttons[move].setClickable(true);

        try{ Thread.sleep(5000); }catch(InterruptedException e){ }

        buttons[move].setVisibility(View.GONE);
        buttons[move].setClickable(false);
    }

}

但是,当我尝试这样做时,整个事情只会冻结 20 秒(大概每次循环 5 秒,但没有任何反应。有什么想法吗?

谢谢。

4

3 回答 3

0

你试过这种方式吗?

private int move;
public void fight() throws InterruptedException
{
    final Random g = new Random();
    runOnUiThread(new Runnable() 
    {
        public void run() {
            while(makeACondition) {
            move = g.nextInt(8);

            toggleButtonState(buttons[move]);
          } 
       }
   });
}

private void toggleButtonState(final Button button)
{
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            if(button.isEnabled())
                button.setVisibility(View.GONE);
            else 
                button.setVisibility(View.VISIBLE);

        }
    }, 5000);

}
于 2012-06-29T05:51:57.573 回答
0

尝试这个

public void fight() throws InterruptedException
{
    Random g = new Random();
    int move;
    runOnUiThread(new Runnable() 
    {
        public void run() {
            while(makeACondition) {
            move = g.nextInt(8);
            buttons[move].setVisibility(View.VISIBLE);
            buttons[move].setClickable(true);

            if (System.currentTimeMillis() % 5000 == 0) {

                buttons[move].setVisibility(View.GONE);
                buttons[move].setClickable(false);
            }
          } 
       }
   }

}
于 2012-06-29T01:07:44.300 回答
0
private Handler mMessageHandler = new Handler();
Random g = new Random();
int move;

private Runnable mUpdaterRunnable = new Runnable() {
    public void run() {
        // hide current button
        buttons[move].setVisibility(View.INVISIBLE);
        // set next button
        move = g.nextInt(8);
        // show next button
        buttons[move].setVisibility(View.VISIBLE);

        // repeat after 5 seconds
        mMessageHandler.postDelayed(mUpdaterRunnable, 5000);
    }
};

首先,使用move = g.nextInt(8);(避免空值)和mMessageHandler.post(mUpdaterRunnable);.

要停下来,mMessageHandler.removeCallbacks(mUpdaterRunnable);

正如 xbonez 所说,您也可以使用 s 来实现这一点TimerTimerTask

于 2012-06-29T01:31:40.543 回答