【问题标题】:Triggering event when Button is pressed down in Android在Android中按下按钮时触发事件
【发布时间】:2011-02-06 14:54:09
【问题描述】:

我有以下适用于 Android 的代码,可以在单击按钮后正常播放声音:

Button SoundButton2 = (Button)findViewById(R.id.sound2);
        SoundButton2.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        mSoundManager.playSound(2);

    }
});

我的问题是我希望在按下按钮时立即播放声音(触摸向下),而不是在释放按钮时(触摸向上)。关于如何实现这一点的任何想法?

【问题讨论】:

    标签: android button


    【解决方案1】:

    你应该这样做: b 是按钮。

    b.setOnTouchListener(new OnTouchListener() {
    
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                        mSoundManager.playSound(2);
                        return true;
                    }
    
                    return false;
                }
            });
    

    【讨论】:

    • 还是出现这些错误: - new View.OnTouchListener(){} 类型必须实现继承的抽象方法 View.OnTouchListener.onTouch(View, MotionEvent) - 方法 onTouch(View, MotionEvent) type new View.OnTouchListener(){} 必须覆盖超类方法 - MotionEvent 无法解析为类型
    • 这两个答案中提供的代码似乎都是正确的。将导入添加到 android.view.MotionEvent。这是OnTouchListener 的文档:developer.android.com/reference/android/view/…
    • 很好,在导入 MotionEvent 并使用这一行后让它工作: if (event.getAction() == MotionEvent.ACTION_DOWN ) {
    • 非常感谢 sw333t! event.equals(MotionEvent.ACTION_UP) 对我也不起作用,您使用 event.getAction() ==MotionEvent.ACTION_DOWN 的解决方案非常完美!
    • 用 sw333t fix 编辑了答案
    【解决方案2】:

    也许使用OnTouchListener?我猜 MotionEvent 会有一些方法来注册对象上的触摸。

       button.setOnTouchListener(new OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
         // TODO Auto-generated method stub
         return false;
        }
       }))
    

    【讨论】:

    • 感谢您的回复。尝试使用该代码时出现以下错误: - new View.OnTouchListener(){} 类型必须实现继承的抽象方法 View.OnTouchListener.onTouch(View, MotionEvent) - new 类型的方法 onTouch(View, MotionEvent) View.OnTouchListener(){} 必须覆盖超类方法 - MotionEvent 无法解析为类型
    • 答案是将编译器级别改为1.6 (stackoverflow.com/questions/1678122/…)
    【解决方案3】:

    import android.view.MotionEvent;

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 2023-03-03
      • 2013-10-11
      • 2018-06-11
      • 2019-06-07
      • 2015-04-28
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多