Android:如何在更新UI的同时创建循环延迟

1 java user-interface android loops delay

这是我在这里的第一篇文章,如果我没有正确格式化我的问题,那就很抱歉.我正在开发我的第一个Android应用程序,它是一个纸牌游戏.我使用visual studio在C#中开发了相同的纸牌游戏.在C#中,为了模拟处理时的动作和延迟等,我将线程休眠一段时间,然后调用Application.DoEvents()方法,强制UI更新.但是,在java中,我似乎无法找到这个问题的答案.

我将从我的deal()方法中发布一些代码,我需要延迟它,看起来这些卡实际上是在一个圆圈中处理,而不是因为计算机速度如此之快而一下子:

private void dealHelper(){Hand pCards = Referee.getHumanHand();

    //show all cards in rotating order
    for(int i=0; i<CARD_COUNT; i++)
    {
        ///////////////////////////////////////////////////////////////////////
        // load each card into their appropriate ImageViews and make visible //
        ///////////////////////////////////////////////////////////////////////

        //human player
        LoadCard(playerCards.get(i), pCards.getCard(i));
        playerCards.get(i).setVisibility(View.VISIBLE);
        playerCards.get(i).setPadding(1, 1, 1, 1);

        // allow discarded cards to be clickable
        discardCardImages.get(i).setPadding(1, 1, 1, 1);

        //computer 1
        computer1Cards.get(i).setImageResource(R.drawable.cardskin);
        computer1Cards.get(i).setVisibility(View.VISIBLE);

        //computer 2
        computer2Cards.get(i).setImageResource(R.drawable.cardskin);
        computer2Cards.get(i).setVisibility(View.VISIBLE);

        //computer 3
        computer3Cards.get(i).setImageResource(R.drawable.cardskin);
        computer3Cards.get(i).setVisibility(View.VISIBLE);
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要在屏幕上显示的每张卡之间稍微延迟约500毫秒来模拟动作.我搜索并搜索过,但没有一个有效的解决方案(或者我理解).任何帮助将非常感激.

谢谢你,丹尼尔

Ben*_*ams 8

使用带有RunnableHandler(在run()中执行循环的一次迭代)和延迟.计算迭代次数,以便知道何时停止并使用最后一个迭代,并调用方法来完成交易完成后需要做的任何事情.postDelayed(Runnable r, long delayMillis)removeCallbacks()


就像是

private final Handler mHandler = new Handler();
private int iLoopCount = 0;

private final Runnable rDealAndWait = new Runnable()
{
  public void run()
  {
    if (dealtAHand())
    {
      ++iLoopCount;
      mHandler.postAtTime(this, SystemClock.uptimeMillis() + DEAL_DELAY);
    }
    else
    {
      doAfterAllHandsDealt();
    }
  }
};


private boolean dealtAHand()
{
  if (i == CARD_COUNT) return false;

  //human player
  LoadCard(playerCards.get(iLoopCount), pCards.getCard(i));
  playerCards.get(iLoopCount).setVisibility(View.VISIBLE);
  playerCards.get(iLoopCount).setPadding(1, 1, 1, 1);

  // etc

  return true;
}
Run Code Online (Sandbox Code Playgroud)

然后在onCreate或任何地方

  dealtAHand();
  mHandler.postAtTime(rDealAndWait, SystemClock.uptimeMillis() + DEAL_DELAY);
Run Code Online (Sandbox Code Playgroud)

}