我正在研究多指手势,我试过使用google手势生成器,但它不支持多指手势,如何在android中识别两指v形手势。
最佳答案
我相信你可以用ScaleGestureDetector
来做这个。
毕竟,顶部的“V”只是一个在Y轴上平移的点。
所以我认为你可以分析焦点和比例因子来确定“V”已经发生了。
这是一个有效的例子。最后我不需要看天平了。有两个灵敏度值可以调整,例如可接受角度的范围和y/x移动的比率。
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.TextView;
public class MainActivity extends Activity {
public static class VListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
private float initialFocusX;
private float initialFocusY;
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
Log.d(TAG, String.format("%.2f,%.2f s:%.2f", detector.getFocusX(),
detector.getFocusY(), detector.getScaleFactor()));
initialFocusX = detector.getFocusX();
initialFocusY = detector.getFocusY();
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
float deltaX = detector.getFocusX() - initialFocusX;
float deltaY = detector.getFocusY() - initialFocusY;
if (deltaY == 0) {
Log.d(TAG, "Not a V, no Y movement");
onNonV();
return;
}
float yMovementRatio = Math.abs(deltaY / deltaX);
if (yMovementRatio < 4) {
Log.d(TAG,
String.format(
"Not a V, the ratio of Y movement to X was not high enough: %.2f",
yMovementRatio));
onNonV();
return;
}
float angle = (float) Math.toDegrees(Math.atan2(deltaY, deltaX));
if (angle > 80 && angle < 100) {
Log.d(TAG, "V!");
onV();
return;
} else {
Log.d(TAG,
String.format(
"Not a V, the angle shows the V was drawn in the wrong direction: %.2f",
angle));
onNonV();
}
}
protected void onV() {
}
protected void onNonV() {
}
}
protected static final String TAG = "MainActivity";
private ScaleGestureDetector mScaleGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t = (TextView) findViewById(R.id.vTextIndicator);
mScaleGestureDetector = new ScaleGestureDetector(this, new VListener() {
@Override
protected void onV() {
t.setText("V!");
}
@Override
protected void onNonV() {
t.setText("Non V");
}
});
}
public boolean onTouchEvent(MotionEvent event) {
boolean retVal = mScaleGestureDetector.onTouchEvent(event);
return retVal || super.onTouchEvent(event);
}
}
activity_main.xml
布局只是:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/vTextIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>