如何在按钮移动时检测事件?

时间:2013-01-26 17:19:18

标签: android ontouchlistener

我正在尝试在android中开发一个乐器应用程序。我为每个按钮实现了OnTouchListener,当我只触摸一个按钮时没有问题。但当我触摸一个按钮并将我的手指移动到下一个按钮时,该按钮的OnTouchListener未被调用且其声音未播放。如何在不按手指的情况下将手指滑动到按钮上时能够播放声音? (我读了很多问题,但没有用)

我的每个按钮的简单OnTouchListener:

final ImageButton img_1 = (ImageButton) findViewById(R.id.img_1);
img_1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
              if( event.getAction() ==  MotionEvent.ACTION_DOWN )   {
                snd.play_s_l_1(); 
              }
             return true;
        } 

 });

1 个答案:

答案 0 :(得分:2)

检查MotionEvent.MOVE:

private Rect rect;    // Variable rect to hold the bounds of the view

public boolean onTouch(View v, MotionEvent event) 
{
    if(event.getAction() == MotionEvent.ACTION_DOWN)
    {
        // Construct a rect of the view's bounds
        rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    }
    if(event.getAction() == MotionEvent.ACTION_MOVE)
    {
        if(!rect.contains((int)event.getX(), (int)event.getY()))
        {
            // User moved outside bounds
        }
    }
    return false;
}