onInterceptTouchEvent的ViewGroup子类

时间:2014-12-10 18:08:13

标签: android subclass ontouchevent viewgroup

我的布局看起来像这样:

enter image description here

我使用的RelativeLayout包含llMainscroll。在llMain,我还有另外两个LinearLayoutsll1ll2。每个LinearLayouts都包含两个Buttons

我希望能够在llMain上的任意位置滑动以调用某个功能。但我也希望能够点击同样位于Buttons的{​​{1}}。

所以我尝试实施llmain。如果我在onInterceptTouchEvent上轻扫我希望Button拦截对onInterceptTouchEvent Button's的来电并执行滑动操作。如果我只是点击onTouchEvent,我就不希望调用Button。相反,我希望调用onInterceptTouchEvent Button's并执行onTouchEvent点击

我为Button创建了Subclass ViewGroup,但我无法正确实现它。它不识别滑动动作,只识别咔嗒声。有人可以看看并帮忙:

llmain

我的public class Game extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.relativeLayout); swipeLinearLayout = new Container(this); //this is supposed to connect to llmain } private class Container extends LinearLayout { public Container(Context context) { super(context); } private float mLastX=0; private float mLastY=0; @Override public boolean onInterceptTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: swipeLayout() //if event recognized as swipe, then swipe break; case MotionEvent.ACTION_MOVE: float x = event.getX(); float y = event.getY(); float xDelta = Math.abs(x - mLastX); float yDelta = Math.abs(y - mLastY); if (yDelta > xDelta) { return true; } break; } return false; } @Override public boolean onTouchEvent(MotionEvent event) { ButtonClick(); //if event is click, then perform button click return true; } } } 无法正确连接到我的swipeLinearLayout。因此,它不会执行滑动或单击操作。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用此GestureDetector:

GestureDetector.OnGestureListener listener = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        Log.d(TAG, "onFling " );
        return true;
    }
};
GestureDetector gestureDetector = new GestureDetector(this, listener);

并在自定义ViewGroup(Container类)中调用它:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    return gestureDetector.onTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
   gestureDetector.onTouchEvent(ev);
   return true;
}