You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OnTouchListener打开新Activity?解决长按时长不足问题

解决FloatingActionButton自定义长按触发时长及跳转问题

一、实现方案

放弃系统自带的OnLongClickListener,改用OnTouchListener配合Handler自定义长按触发延迟,同时确保跳转逻辑正确执行。

二、完整代码示例

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton actionButton = findViewById(R.id.action_button);
    // 自定义长按触发时长,这里设为2000毫秒(可按需调整)
    final long LONG_PRESS_TRIGGER_TIME = 2000;
    Handler handler = new Handler();
    Runnable longPressTask = new Runnable() {
        @Override
        public void run() {
            openWebsite();
        }
    };

    actionButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 按下按钮时启动延迟任务
                    handler.postDelayed(longPressTask, LONG_PRESS_TRIGGER_TIME);
                    return true;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    // 松开或触摸中断时取消延迟任务,避免误触发
                    handler.removeCallbacks(longPressTask);
                    return true;
                default:
                    return false;
            }
        }
    });

    defineView();
    handleIntent();
    defineActionBar();
    checkPermission();
}

public void openWebsite() {
    Intent intent = new Intent(this, Website.class);
    startActivity(intent);
}

三、注意事项

  • 务必确认Website Activity已在AndroidManifest.xml中注册,否则会跳转失败:
    <activity android:name=".Website" />
    
  • LONG_PRESS_TRIGGER_TIME可根据需求修改数值,单位为毫秒
  • 返回true表示消费触摸事件,避免后续触发系统默认的点击/长按逻辑

内容的提问来源于stack exchange,提问作者Xtra 514

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:54:24