LoginSignup
10
10

More than 5 years have passed since last update.

子ビューのタッチイベントをインターセプトしてGestureDetectorでフリックを感知するViewGroup

Last updated at Posted at 2014-08-12

子ビューのタッチイベントをインターセプト

結局使わなかったのだけれども、せっかくなので。
子ビューへAtachされるイベントを間でViewGroupにインターセプトさせて、
親側のOnGestureDetectorListenerへイベントをハンドリングしているが、
return falseなので子ViewのOnClickEventListnerも動きます。

FlickRelativeLayout.java
package jp.sample.app.lib.ViewGroup;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

/**
 * Created by yusukehoshi on 2014/08/12.
 */
public class FlickRelativeLayout extends RelativeLayout implements GestureDetector.OnGestureListener {
    protected GestureDetector gd;

    public FlickRelativeLayout(Context context) {
        super(context);
        init();
    }

    public FlickRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FlickRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void init(){
        gd = new GestureDetector(getContext(),this);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev){
        super.onInterceptTouchEvent(ev);
        gd.onTouchEvent(ev);
        return false;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        Log.d("test", "vx:" + velocityX + " vy:" + velocityY);
        return false;
   }
}

普通にRelativeLayoutを置き換えて使えます。
ほかのLayoutでやりたい場合は継承元を変えてください。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10