1.设置长按时间
java
//长按五秒事件
private void startLongClickTimer() {
if (longClickRunnable == null) {
longClickRunnable = new Runnable() {
@Override
public void run() {
// 在这里执行长按事件
showPasswordDialog();
Toast.makeText(UseSmileActivity.this, "长按事件触发", Toast.LENGTH_SHORT).show();
}
};
}
// 延迟五秒钟执行长按事件
handlerBack.postDelayed(longClickRunnable, 5000); // 5000 毫秒即五秒钟
}
2、删除计时器
java
//抬起手指删除计时器
private void cancelLongClickTimer() {
if (longClickRunnable != null) {
handlerBack.removeCallbacks(longClickRunnable);
}
}
3、弹出的密码输入框与业务逻辑
java
//弹出密码输入框
private void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("输入密码后退出");
// 设置密码输入框
final EditText input = new EditText(this);
builder.setView(input);
builder.setPositiveButton("确定", (dialog, which) -> {
String password = input.getText().toString().trim();
if (checkPassword(password)) {
// 密码正确,执行相应操作
Toast.makeText(UseSmileActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
finish();
// 这里可以执行密码验证通过后的操作
} else {
// 密码错误,给出提示
Toast.makeText(UseSmileActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", (dialog, which) -> {
dialog.cancel();
});
// 显示 AlertDialog
builder.show();
}
4、文本绑定事件
java
TextView info5 = (TextView) findViewById(R.id.info5);
info5.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 按下时启动计时器
startLongClickTimer();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// 抬起或取消时移除计时器
cancelLongClickTimer();
return true;
}
return false;
}
});