具有多个视图的Android触摸事件(例如,在一个Viewflipper一个ListView)
Android touch events with multiple views(such as a ListView in a Viewflipper)
当我把里面FlingGallery一个ListView,当我我一扔手指FlingGallery无法工作。
When i put a ListView inside the FlingGallery, the FlingGallery can't work when i Fling my finger.
写ViewFlipper的扩展,其所有的孩子设置自定义触摸监听器,这样的:
Write an extension of ViewFlipper and for all of its children set custom touch listener, like that:
public void addView(View child, int index, android.view.ViewGroup.LayoutParams params) {
child.setOnTouchListener(new DragableViewTouchListener());
}
/**
* To organize horizontal paging every child should use this implementation of OnTouchListener.
*/
private class DragableViewTouchListener implements OnTouchListener {
private static final int DISTANCE_WHEN_DO_SCROLL = 5;
private float historyDistanceX = 0;
private float historyDistanceY = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE && event.getHistorySize() > 0) {
historyDistanceX = event.getHistoricalX(event.getHistorySize() - 1) - event.getX();
historyDistanceY = event.getHistoricalY(event.getHistorySize() - 1) - event.getY();
}
boolean actionUp = (event.getAction() == MotionEvent.ACTION_UP) || (event.getAction() == MotionEvent.ACTION_CANCEL);
if (actionUp) {
boolean horizontalStrongerThanVertical = Math.abs(historyDistanceX) > Math.abs(historyDistanceY);
if (Math.abs(historyDistanceX) > DISTANCE_WHEN_DO_SCROLL && horizontalStrongerThanVertical) {
onHorizontalScroll(historyDistanceX);
historyDistanceX = 0;
historyDistanceY = 0;
return true;
}
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
return true;
}
return false;
}
private void onHorizontalScroll(float distanceX) {
if (distanceX > 0) {
showNext();
}
else {
showPrevious();
}
}
};
主要的想法是分离水平运动事件(它们分派到ViewFlipper)和垂直运动事件(它们分派给孩子(到ListView控件))
The main idea is to separate horizontal motion events (dispatch them to ViewFlipper) and vertical motion events (dispatch them to child (to ListView))