Android,Sleep在一行代码中没有阻止UI请

时间:2016-12-27 19:38:04

标签: android

这是我正在写的纸牌游戏的一部分,注意mHandler.postDelayed一行,你不能真的除了我每次需要UI线程睡觉时写它吗?我怎样才能使它成为一行代码?

    public void onDealClick(View view) {
    reset();
    view.setVisibility(View.GONE);
    if (mBalance - mBetAmount < 0) {
        showToast("Not enough chips! Resetting your chips to 1000");
        mBalance = 1000;
    }
    mBalance -= mBetAmount;
    mBalanceTextView.setText("Balance: " + mBalance);
    mPlayerHand.dealACard(mDeck, true);
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mDealerHand.dealACard(mDeck, true);
        }
    }, 1000);
    mPlayerHand.dealACard(mDeck, true);
    mDealerHand.dealACard(mDeck, false);
    mPlayerHand.updateHandValueText();
    if (mPlayerHand.getCard(0).getValue() == mPlayerHand.getCard(1).getValue()) {
        mPlayerOptions.showButtons(
                PlayerOptions.HIT,
                PlayerOptions.STAND,
                PlayerOptions.SURRENDER,
                PlayerOptions.DOUBLE,
                PlayerOptions.SPLIT);
    } else {
        mPlayerOptions.showButtons(PlayerOptions.HIT, PlayerOptions.STAND, PlayerOptions.SURRENDER, PlayerOptions.DOUBLE);
    }
    if (mPlayerHand.getmHardValue() == 21) {
        endOfHand((int)(mBetAmount * 2.5), "BLACKJACK! You Win ", " Chips");
    }
}

这部分我想缩短

    mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        mDealerHand.dealACard(mDeck, true);
    }
}, 1000);

2 个答案:

答案 0 :(得分:0)

字面答案:

dealTheDealerACardInOneSecond();

是一个单行,称为此方法

private void dealTheDealerACardInOneSecond() {
    mHandler.postDelayed(new Runnable() {
    @Override
    public void run() {
        mDealerHand.dealACard(mDeck, true);
    }
   }, 1000);
}

但是真的看起来你的游戏架构是错误的,我不确定那个延迟是什么,也许是动画,但是你需要重新思考(我不确定你想要实现什么,所以不能甚至给你一个指针)

答案 1 :(得分:0)

您可以将lambdas用于Runnable

() -> mDealerHand.dealACard(mDeck, true);

这等于你的Runnable

new Runnable() {
@Override
public void run() {
    mDealerHand.dealACard(mDeck, true);
  }
};