是的,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消息。