当用户手指以编程方式进入视图时,有没有办法收听? 我想要的是当用户将手指移到视图之外时,用户手指在视图中具有不同的状态。
我知道这可以通过xml来完成,但因为我使用的是第三方库,所以我不允许这样做,所以我必须找到一种方法来编程。
答案 0 :(得分:1)
在视图上设置触控侦听器并比较x和y点
http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent)
记录用户触摸的起始位置
http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_DOWN
然后跟踪偏移量。
这是我为另一个问题写的一些视图监听器代码:
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;
}
});
}