繁体   English   中英

如果条件为真,我如何每秒自动运行一个按钮?

[英]How can i run a button automatically every second until de if condition be true?

我需要一个按钮可以每1-2秒自动运行一次,并且当满足if条件(我在该按钮所使用的方法中具有的条件)满足时,必须停止此功能。

我已经尝试过了,但这不是我想要的,因为使用此代码,按钮仅运行一次:

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            Consulta.performClick();

        }
    }, 1000);

我的按钮的onClick:

 public void consultaBD(View view)
{

    DB db = new DB(getApplicationContext(),null,null,1);
    String buscar = text_view.getText().toString();
    String[] datos;
    datos=db.buscar_reg(buscar.trim());
    db.infraccion(buscar.trim());

    if(datos[2] =="Encontrado")
    {

        App.matricula=buscar;
        startActivity(new Intent(getApplicationContext(), MatriculasActivity.class));
        Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();

    }
    else
    {
        Toast.makeText(getApplicationContext(),datos[2],Toast.LENGTH_SHORT).show();

    }

}

另一种方法是使用计时器每x秒启动一次按钮单击。 但是,在此答案中,我将坚持使用您使用的方法。 您的处理程序似乎不正确,请尝试如下操作:

将您的处理程序替换为:

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Consulta.performClick();
        handler.postDelayed(this, 1000);
    }
};

并使用以下命令启动它:(其中1000是每次执行之间的时间(以毫秒为单位))

handler.postDelayed(runnable, 1000);

更新:

您还要求更改文本框内的文本时触发该事件。 为此,您需要创建一个新的事件侦听器(确保将field1替换为对文本框的实际引用):

field1.addTextChangedListener(new TextWatcher() {

   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {

         /* Add the Handler Call here */
         handler.postDelayed(runnable, 1000);

     }
});

无论我了解什么上下文,这里的原始代码都可以为您提供帮助。

Handler handler = new Handler();

//initialize this method once by either clicking on button or as the activity starts
void checkAndPerformClick(boolean conditionFulfilled) {

    if (conditionFulfilled) {
        handler.removeCallbacksAndMessages(null);
        return;
    }

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Consulta.performClick();
            checkAndPerformClick(datosEqualsEncontrado());
        }
    }, 1000);
}

boolean datosEqualsEncontrado() {
    // apply your logic here as the name suggests
    return false;
}

暂无
暂无

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

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