在Android中几秒后,按钮出现然后消失

时间:2012-06-29 01:02:51

标签: android

我有几个按钮,我想随机出现,几秒后消失。如果它发生任何变化,我也希望它们在可见时可点击。

这就是我所拥有的:

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秒钟,没有任何反应。任何想法?

感谢。

3 个答案:

答案 0 :(得分: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);
            }
          } 
       }
   }

}

答案 1 :(得分: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所说,你也可以使用TimerTimerTask来实现这一点。

答案 2 :(得分: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);

}