【问题标题】:How to do something repeatedly while a button is pressed?按下按钮时如何重复执行某些操作?
【发布时间】:2012-11-15 01:04:52
【问题描述】:

我正在使用特定中间件(不重要)在 Android 中开发 TV-Remote Simulator 应用。

在音量按钮(音量+和音量-)的情况下,我要做的是在按下按钮时重复发送“音量调高”信号。

这就是我最后尝试的(其中一个按钮的代码,另一个必须相同,除了名称):

  1. 声明一个布尔变量

    boolean pressedUp = false;
    
  2. 使用以下 AsyncTask 声明了一个内部类:

    class SendVolumeUpTask extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected Void doInBackground(Void... arg0) {
            while(pressedUp) {
                SendVolumeUpSignal();
        }
        return null;
    }
    

    }

  3. 为按钮添加监听器:

    final Button buttonVolumeUp = (Button) findViewById(R.id.volup);
    buttonVolumeUp.setOnTouchListener(new View.OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
    
            case MotionEvent.ACTION_DOWN:
    
                if(pressedUp == false){
                    pressedUp = true;
                    new SendVolumeUpTask().execute();
                }
    
            case MotionEvent.ACTION_UP:
    
                pressedUp = false;
    
        }
            return true;
        }
    });
    

我也尝试过使用Increment-Decrement counter while button is pressed 中的简单线程,但都没有成功。该应用程序可以很好地处理其余按钮(通道等),但完全忽略了音量变化。

【问题讨论】:

    标签: android button touch-event ontouchlistener


    【解决方案1】:

    您忘记添加中断;在 MotionEvent.ACTION_DOWN: 案例的末尾。这意味着行pressedUp = false;即使在那个动作上也会被执行。正确的做法是:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
    
        case MotionEvent.ACTION_DOWN:
    
            if(pressedUp == false){
                pressedUp = true;
                new SendVolumeUpTask().execute();
            }
        break;
        case MotionEvent.ACTION_UP:
    
            pressedUp = false;
    
    }
        return true;
    }
    

    【讨论】:

    • 谢谢,现在信号已发送。但是,它会在短时间内发出大量信号。也许计数器应该可以工作。
    • 我建议在调用 SendVolumeUpSignal() 之间有一个间隔;例如试试这个:while(pressedUp) { SendVolumeUpSignal(); Thread.sleep(100);}
    【解决方案2】:

    你考虑过

    • onKeyDown 事件上开始你的重复任务
    • 停止onKeyUp 上的任务 活动?

    【讨论】:

    • 不就是设备物理按键的那些方法吗?我的意思是远程应用程序中的触觉对象
    • 是的,顾名思义是这样......但它们不是:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多