2015-02-17 50 views
0

之外的運動。我有一個RelativeLayout的監聽器:檢測一按,然後視圖

rl.setOnTouchListener(new OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       rl.setBackgroundColor(Color.BLACK); 
      } 

      if ((event.getAction() == MotionEvent.ACTION_UP)) { 
       rl.setBackgroundColor(Color.WHITE); 
       v.performClick(); 
      } 
      return false; 
     } 
    }); 

這當我按下/上的佈局改變顏色。我想要檢測的是用戶何時按下屏幕,但將手指從視圖中移開(但仍然按下)。我不知道如何去做這件事。謝謝。

回答

2

你在這裏。應該使背景變黑,然後變白。如果手指移出視野,它會返回到白色。

rl.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 
     if (motionEvent.getAction() == MotionEvent.ACTION_UP) { 
      if (isTouchInView(view, motionEvent)) { 
       //lifted finger while touch was in view 
       view.performClick(); 
      } 

      view.setBackgroundColor(Color.WHITE); 
      return true; 
     } 

     if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) { 
      //finger still down and left view 
      if (!isTouchInView(view, motionEvent)) { 
       view.setBackgroundColor(Color.WHITE); 
      } 
     } 

     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
      //pressed down on view 
      view.setBackgroundColor(Color.BLACK); 
      return true; 
     } 

     if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { 
      //a cancel event was received, finger up out of view 
      view.setBackgroundColor(Color.WHITE); 
      return true; 
     } 
     return false; 
    } 

    private boolean isTouchInView(View view, MotionEvent event) { 
     Rect hitBox = new Rect(); 
     view.getGlobalVisibleRect(hitBox); 
     return hitBox.contains((int) event.getRawX(), (int) event.getRawY()); 
    } 
+0

您的isTouchInView方法正是我所期待的。非常感謝! – user1282637 2015-02-17 21:24:00

+1

歡迎您!那也是我給的麻煩。快樂的編碼。 – 2015-02-17 21:28:31

相關問題