我正在尝试处理来自用户手指的滑动。我按照示例here进行了操作。从那个例子中我得到了以下代码:
public class GameScreen extends Activity implements OnTouchListener {
TextView tv;
private final GestureDetector gestureDetector = new GestureDetector(getBaseContext(), new GestureListener());
public boolean onTouch(final View view, final MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeTop() {
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeBottom() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gamescreen);
tv = (TextView)findViewById(R.id.textview);
tv.setOnTouchListener(new OnSwipeTouchListener() { // ERROR: "The method setOnTouchListener(View.onTouchListener) in the type View is not applicable for the arguments (new OnSwipeTouchListener(){})
public void onSwipeTop() {
Toast.makeText(GameScreen.this, "top", Toast.LENGTH_SHORT).show();
}
public void onSwipeRight() {
Toast.makeText(GameScreen.this, "right", Toast.LENGTH_SHORT).show();
}
public void onSwipeLeft() {
Toast.makeText(GameScreen.this, "left", Toast.LENGTH_SHORT).show();
}
public void onSwipeBottom() {
Toast.makeText(GameScreen.this, "bottom", Toast.LENGTH_SHORT).show();
}
});
}
}
请注意我在错误消息中注释的onCreate()
方法中代码底部附近。我试图让这段代码正常工作,以便显示Toasts
通知我滑动手势正在运行。
我的问题是,我在代码中做错了什么?