1.设置长按时间
//长按五秒事件private void startLongClickTimer() {if (longClickRunnable == null) {longClickRunnable = new Runnable() {@Overridepublic void run() {// 在这里执行长按事件showPasswordDialog();Toast.makeText(UseSmileActivity.this, "长按事件触发", Toast.LENGTH_SHORT).show();}};}// 延迟五秒钟执行长按事件handlerBack.postDelayed(longClickRunnable, 5000); // 5000 毫秒即五秒钟}
2、删除计时器
//抬起手指删除计时器private void cancelLongClickTimer() {if (longClickRunnable != null) {handlerBack.removeCallbacks(longClickRunnable);}}
3、弹出的密码输入框与业务逻辑
//弹出密码输入框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();});// 显示 AlertDialogbuilder.show();}
4、文本绑定事件
TextView info5 = (TextView) findViewById(R.id.info5);info5.setOnTouchListener(new View.OnTouchListener() {@Overridepublic 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;}});