簡體   English   中英

在Android中幾秒鍾后出現“使”按鈕消失,然后消失

[英]Make button appear and then disappear after a few seconds in 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秒,什么也沒發生。有什么想法嗎?

謝謝。

嘗試這個

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

}
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); (避免為null)和mMessageHandler.post(mUpdaterRunnable);

要停止,請mMessageHandler.removeCallbacks(mUpdaterRunnable);

如xbonez所說,您也可以使用帶有TimerTaskTimer實現此目的。

您嘗試過這種方式嗎?

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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM