【问题标题】:Press a Button just one time只需按一次按钮
【发布时间】:2014-05-25 19:56:55
【问题描述】:

我试图按一次第一个按钮。这个按钮通常会返回一张随机卡片,但我只想要一次。然后按钮应该是非活动的。我怎样才能做到这一点? 这是我的代码:

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

【问题讨论】:

  • 在 onClick 内:background.setEnabled(false);你试过这样的事情吗?
  • 是的,我试过了。它让我可以按一次按钮,但我只需要按两次
  • 保留一个统计点击次数的静态计数器。如果 timesClicked > 1 -> setEnabled(false);
  • 试试,也有一个循环,但没有任何改变
  • 你为什么会有一个循环?这没有什么意义。你是怎么实现的?

标签: java android eclipse


【解决方案1】:

你可以禁用你的按钮(把它放在你的 onClick 中)

background.setEnabled(false);

您也可以在 onCreate 方法中将按钮初始化为 true

【讨论】:

    【解决方案2】:

    如果玩家接下来有动作要做,更简单的方法是在第一次按下按钮时停用按钮,然后在下一个动作再次激活时停用。

    你可以这样做添加

    background.setEnabled(false);
    

    在你的匿名类监听器中和添加之后

    background.setEnabled(true);
    

    在玩家的下一步行动中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多