是的,Android的GestureDetector可以識別旋轉手勢。你可以通過實現OnGestureListener
接口并重寫onFling()
方法來檢測旋轉手勢。以下是一個簡單的示例:
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class RotationGestureDetector implements GestureDetector.OnGestureListener {
private GestureDetector gestureDetector;
public RotationGestureDetector(Context context) {
gestureDetector = new GestureDetector(context, this);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float angle = getAngle(e1, e2);
if (Math.abs(angle) > 10) { // 設置一個閾值,可以根據需要調整
Toast.makeText(gestureDetector.getContext(), "旋轉角度: " + angle, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private float getAngle(MotionEvent e1, MotionEvent e2) {
float centerX1 = (e1.getX() + e1.getX() / 2);
float centerY1 = (e1.getY() + e1.getY() / 2);
float centerX2 = (e2.getX() + e2.getX() / 2);
float centerY2 = (e2.getY() + e2.getY() / 2);
float distanceX = centerX2 - centerX1;
float distanceY = centerY2 - centerY1;
return (float) Math.toDegrees(Math.atan2(distanceY, distanceX));
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
public void setOnGestureListener(View view) {
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
}
}
在你的Activity中,你可以這樣使用這個類:
RotationGestureDetector rotationGestureDetector = new RotationGestureDetector(this);
rotationGestureDetector.setOnGestureListener(findViewById(R.id.your_view));
這樣,當用戶在指定視圖上執行旋轉手勢時,應用程序會檢測到旋轉角度并顯示一個Toast消息。