简体   繁体   English

一次按下一个按钮

[英]Press a Button just one time

I'm trying to press the first button just one time. 我试图只按一次第一个按钮。 This button usually return a random card but I want it just one time. 这个按钮通常会返回一张随机卡片,但我只想要一次。 Then the button should be inactive. 然后,该按钮应处于非活动状态。 How can I do that? 我怎样才能做到这一点? That's my code: 那是我的代码:

public class GameActivity extends Activity {
    Boolean buttonPressed = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

    final Button background = (Button) findViewById(R.id.A);
    Resources res = getResources();
    final TypedArray Deck = res.obtainTypedArray(R.array.Deck);
    final Random random = new Random(); 
    if (!buttonPressed){
        buttonPressed = true;
    background.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View v) { 

            //Genrate a random index in the range
            int randomInt = random.nextInt(Deck.length()-1);
            // Generate the drawableID from the randomInt
            int drawableID = Deck.getResourceId(randomInt, -1);
            background.setBackgroundResource(drawableID);
        }
         });

If the player has an action to do next, the simpler way is to deactivate the button when is pressed first time and after in the next action activated again. 如果玩家有下一步要做的动作,则更简单的方法是在第一次按下该按钮时停用该按钮,然后在再次激活下一个动作之后将其停用。

You can do this adding 您可以添加

background.setEnabled(false);

in your anonymous class listener and after add 在您的匿名类侦听器中,然后添加

background.setEnabled(true);

in player's next action. 在玩家的下一个动作中。

you can disable your button with (place it inside your onClick) 您可以使用禁用按钮(将其放在onClick内)

background.setEnabled(false);

and you also might initialize your button to true in onCreate method 而且您也可以在onCreate方法中将按钮初始化为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM