在Android中,GestureDetector類用于檢測復雜的手勢。要實現新手勢識別,你需要擴展GestureDetector類并重寫其onFling()、onScroll()等方法。以下是一個簡單的示例,展示了如何創建一個自定義手勢識別器來檢測雙擊和滑動手勢:
CustomGestureDetector
的類,繼承自GestureDetector
:import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class CustomGestureDetector extends GestureDetector {
private static final int DOUBLE_TAP_TIME_INTERVAL = 300; // 雙擊時間間隔,單位毫秒
private long mLastTapTime = 0;
public CustomGestureDetector(Context context) {
super(context, new GestureListener());
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// 在這里處理滑動手勢
return super.onFling(e1, e2, velocityX, velocityY);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
long currentTime = SystemClock.elapsedRealtime();
if (currentTime - mLastTapTime <= DOUBLE_TAP_TIME_INTERVAL) {
// 雙擊事件
return true;
} else {
mLastTapTime = currentTime;
return super.onSingleTapConfirmed(e);
}
}
}
}
CustomGestureDetector
來檢測手勢:import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private CustomGestureDetector mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new CustomGestureDetector(this);
View contentView = findViewById(R.id.content_view);
contentView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
});
}
}
現在,你已經創建了一個可以檢測雙擊和滑動手勢的自定義手勢識別器。你可以根據需要擴展此類以處理其他手勢。