2012-09-06 27 views
1

有没有什么办法来监听当用户手指在视图内编程? 我想要的是,当用户将手指放在视图外时,视图内的用户手指具有不同的状态。以编程方式在视图中侦听?

我知道这可以通过xml来完成,但是因为我使用的是第三方库,它不允许我这样做,所以我必须找到一种以编程方式执行此操作的方法。

回答

1

设置在视图上的触摸侦听和当起始当前位置,其中,用户触摸向下

http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_DOWN

,然后跟踪比较x和y斑点

http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent

记录偏移量。

这里是一些观点听众代码,我写了另一个问题:

float initialX = 0; 
float initialY = 0; 
int currentFocusedChild = 0; 
List<View> children; 

public void walkElements() { 
    final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout); 
    children = mainLayout.getFocusables(View.FOCUS_FORWARD); 
    mainLayout.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch(event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        initialX = event.getX(); 
        initialY = event.getY();       
        break; 
       case MotionEvent.ACTION_MOVE: 
        float diffX = event.getX() - initialX; 
        float diffY = event.getY() - initialY; 

        if(diffY > 0) { 
         if (currentFocusedChild < children.size() - 1) { 
          currentFocusedChild++; 
         } 
        } else { 
         if (currentFocusedChild > 0) { 
          currentFocusedChild--; 
         } 
        } 
        children.get(currentFocusedChild).setSelected(true); 

        //Sleep for a period of time so the selection is slow enough for the user. 
        Thread.sleep(300); 
        break; 
       case MotionEvent.ACTION_UP: 
        children.get(currentFocusedChild).performClick(); 
        break; 
      } 
      return false; 
     } 
    }); 

}