Android 长按文本弹出输入框

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;
            }
        });
相关推荐
一晌小贪欢8 分钟前
【Python数据分析】数据分析与可视化
开发语言·python·数据分析·数据可视化·数据清洗
沐浴露z10 分钟前
【微服务】基本概念介绍
java·微服务
Z3r4y40 分钟前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
草莓火锅2 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_2 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
DreamNotOver2 小时前
批量转换论文正文引用为上标
开发语言·论文上标
散峰而望2 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng2 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
Jooou2 小时前
Spring事务实现原理深度解析:从源码到架构全面剖析
java·spring·架构·事务