如果我有2个按钮,如何在Android Studio中按特定顺序和特定时间段点击一系列按钮后实现某些功能

问题描述 投票:-1回答:1

如果我在android工作室中有2个按钮,并且如果我想在某个顺序和特定时间段内按下2个按钮时实现某些功能,那么代码将如何?假设有2个按钮,button1和button2,如果在按钮1,button2,button2,button1中按下按钮,则执行一些激活。 button1.onClick ----(1秒内)---> button2.onClick ----(1秒内)---> button2.onClick ----(1秒内)---> button1。 onClick ----->然后做一些活动。我希望这能解释我想要实现的目标。任何帮助深表感谢。 :)

更新这是我到目前为止所得到的,但我甚至不确定这是否是正确的方法

我为两者都设置了一个点击监听器

buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);

然后

public void onClick(View view) {
  if(view == buttonOne) {
    //a timer for 1 second {
      if(view == buttonTwo) {
        //a timer for 1 second {
          if(view == buttonTwo) {
            //a timer for 1 second {
              if(view == buttonOne) {
                startActivity(new Intent(this, Some.class));
              }
            }
          }
        }
      }
    }
  }
}
java android android-studio
1个回答
0
投票

该解决方案通过使用处理程序并延迟为此案例做一段时间的事情1秒钟。因为所有按钮都有整数id,所以解决方案将以正确的顺序为你准备一个整数数组,你可以稍后在一个数组中循环检查它中的id,将它与你的按钮的id进行比较。最初所有按钮ID都为零(0),如果用户点击按钮,如果他在1秒钟内没有点击任何其他按钮,他将添加正确的整数id。数组中的所有ID将再次为零(0),除非最后一次单击是第4次单击,之后您必须自己检查数组来处理逻辑。

让我们首先声明我们将使用的变量(记住阅读评论):

private Handler handler; //handler to delay all work in 1 second
private Runnable runnable; //runnable this will be doing the job in another thread
private int[] buttonIDs = {0, 0, 0, 0}; //all button ids are zero initially
private int pressNumber=-1; //The user has not clicked anything

这是您必须在课堂中添加的两种方法。

第一种方法:

private void startCounter() {

    handler = new Handler();
    runnable = new Runnable() {

    @Override
    public void run() {
        if(buttonIDs[3]==0){ // if the last id is still zero lets clear everything and start afresh
             clearEverything();
          }                       
    }
 }
    handler.postDelayed(runnable,1000); // we tell it dont execute the code in run until a 1000 milliseconds which is 1 second
}

第二种方法是:

private void clearEverything(){
     // clear everything will really start everything afresh always call this method first if you want to repeat the game start afresh
     pressNumber=-1;
     for(int i=0;i < 4;i++) {
        buttonIDs[i] = 0;
     }
}

onClick里面的代码最终就是这样:

if(pressNumber < 3){
   pressNumber++; //increment the pressing to another value
   buttonIDs[pressNumber] = view.getId(); //use that value as index to button id
   if(runnable != null){
          handler.removeCallbacks(runnable); // if there was any handler still running cancel it first because we have clicked some button
   }
   startCounter(); //after click always start counter and remember if the counter finishes it will reset everything
} else{

 //Do something here the user has clicked all the buttons 4 times without delaying 1 second each!. The order of button clicks is the integer array buttonIDs and you can clearEverything(); to start again!

}
© www.soinside.com 2019 - 2024. All rights reserved.