Android双击返回键退出程序的3种写法

751
2023/8/16 17:03:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  1. 使用onBackPressed()方法:

@Override

public void onBackPressed() {

super.onBackPressed();

// 退出程序的操作

finish();

}

  1. 使用双击返回键的计时器:

private static final long DOUBLE_BACK_PRESS_TIME = 2000; // 双击返回键的间隔时间

private long backPressTime;

@Override

public void onBackPressed() {

if (backPressTime + DOUBLE_BACK_PRESS_TIME > System.currentTimeMillis()) {

super.onBackPressed();

// 退出程序的操作

finish();

} else {

Toast.makeText(this, “再次点击返回键退出程序”, Toast.LENGTH_SHORT).show();

}

backPressTime = System.currentTimeMillis();

}

  1. 使用手势库GestureDetector:

private static final int SWIPE_THRESHOLD = 100; // 手势的阈值

private static final int SWIPE_VELOCITY_THRESHOLD = 100; // 手势的速度阈值

private GestureDetector gestureDetector;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// 初始化GestureDetector

gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

@Override

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

// 计算手势的速度和方向

float deltaX = e2.getX() - e1.getX();

float deltaY = e2.getY() - e1.getY();

if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {

if (deltaX > 0) {

// 右滑动,退出程序的操作

finish();

}

}

return super.onFling(e1, e2, velocityX, velocityY);

}

});

}

@Override

public boolean onTouchEvent(MotionEvent event) {

// 将触摸事件传递给GestureDetector处理

gestureDetector.onTouchEvent(event);

return super.onTouchEvent(event);

}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: android中slider的用途有哪些