我想从按钮更改为滑动,以便获取我的Android应用程序中的下一个和上一个元素。我已经看过Gestures的一些实现,主要是在stackoverflow中,但是在编写类似的代码后,它似乎不起作用。我想知道为什么我会想念。我只想实现向右滑动和向左滑动以获取下一个和上一个元素。这是应用程序中有关此问题的相关部分。谢谢
public class MainActivity extends AppCompatActivity {
public GestureDetector gestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.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();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
Toast.makeText(MainActivity.this, "Swipe Right", Toast.LENGTH_SHORT).show();
}
public void onSwipeLeft() {
Toast.makeText(MainActivity.this, "Swipe Left", Toast.LENGTH_SHORT).show();
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
}