Skip to content

Instantly share code, notes, and snippets.

@hiyorineko
Created January 22, 2016 02:34
Show Gist options
  • Save hiyorineko/22d60e9289c04f25ac8e to your computer and use it in GitHub Desktop.
Save hiyorineko/22d60e9289c04f25ac8e to your computer and use it in GitHub Desktop.
ビューのフリック
ImageView iv;
TextView tv;
// X軸最低スワイプ距離
private static final int SWIPE_MIN_DISTANCE = 50;
// X軸最低スワイプスピード
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
// Y軸の移動距離 これ以上なら横移動を判定しない
private static final int SWIPE_MAX_OFF_PATH = 250;
// タッチイベントを処理するためのインタフェース
private GestureDetector mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetector(this, mOnGestureListener);
iv = (ImageView)findViewById(R.id.iv);
iv.setOnTouchListener(this);
tv = (TextView)findViewById(R.id.tv);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
// タッチイベントのリスナー
private final GestureDetector.SimpleOnGestureListener mOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
// フリックイベント
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
try {
// 移動距離・スピードを出力
float distance_x = Math.abs((event1.getX() - event2.getX()));
float velocity_x = Math.abs(velocityX);
tv.setText("横の移動距離:" + distance_x + " 横の移動スピード:" + velocity_x);
// Y軸の移動距離が大きすぎる場合
if (Math.abs(event1.getY() - event2.getY()) > SWIPE_MAX_OFF_PATH) {
tv.setText("縦の移動距離が大きすぎ");
}
// 開始位置から終了位置の移動距離が指定値より大きい
// X軸の移動速度が指定値より大きい
else if (event1.getX() - event2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
tv.setText("右から左");
}
// 終了位置から開始位置の移動距離が指定値より大きい
// X軸の移動速度が指定値より大きい
else if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
tv.setText("左から右");
}
} catch (Exception e) {
// TODO
}
return false;
}
};
}
@hiyorineko
Copy link
Author

結果としてImageViewのフリック→TextViewに表示に成功。
onTouchとonTouchEvent両方同じ処理を書いてるあたりが理解できてない(TouchListenerの投げ方を他に知らなかったので書いてるだけ)
onTouchEventを消すとフリック検知をしなくなる。
onTouchを消すとTouchListenerが投げれなくなる。

参考
http://takeshiyako.blogspot.jp/2015/08/android-flick-input-event.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment