如何设置imagebutton的侦听器,以便在触摸位置移出或移入imagebutton时注意到?

pgccezyw  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(168)

我正在用java为android制作一个简单的钢琴应用程序,我刚刚设置了 setOnTouchedListener 对每个 ImageButtons . 如果 MotionEventACTION_DOWN ,钢琴声响起。如果 MotionEventACTION_UP ,钢琴声停止了。但如果我把手指从 ImageButton ,声音还在播放。我想当我把手指从地板上拽出来的时候声音就停止 ImageButton . 如果我拖进去 ImageButton ,我想再播放一次声音。。。我应该使用什么侦听器?

public class KeyBoardListener implements View.OnTouchListener {
    private SoundPool spool;
    private int soundkeys[];
    private int pitch;
    private boolean isWhite;
    public void setInitSound(SoundPool spool, int soundkeys[], int pitch, boolean isWhite){ // 리스너에서 재생할 SoundPool 가져옴
        this.soundkeys=soundkeys;
        this.spool=spool;
        this.pitch=pitch;
        this.isWhite=isWhite;
    }
        @Override       // 건반 이미지뷰 터치리스너
        public boolean onTouch (View view, MotionEvent motionEvent){
            int currentpitch=pitch+KeyboardActivity.octave.get()*12;     // 옥타브 값 적용
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                float y = motionEvent.getY();   // 터치한 Y좌표와 건반 최대 Y좌표 이용해 벨로시티 값 계산
                float ymax=view.getHeight();
                y=y/ymax;
                PlayNote.noteOff(spool, currentpitch);
                PlayNote.noteOn(spool, soundkeys[currentpitch], currentpitch, y);
                if(isWhite)
                    view.setBackgroundColor(Color.parseColor("#B0B0B0"));
                else
                    view.setBackgroundResource(R.drawable.key_black_push);
            }
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (KeyboardActivity.sustain.get() == false)  // 서스테인 기능이 꺼져있을 때만 소리 정지
                    PlayNote.noteOff(spool, currentpitch);
                if(isWhite)
                    view.setBackgroundColor(Color.WHITE);
                else
                    view.setBackgroundResource(R.drawable.key_black);
            }
            return false;
        }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题