如何使用OnTouchListener打开新Activity?解决长按时长不足问题
一、实现方案
放弃系统自带的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); }
三、注意事项
- 务必确认
WebsiteActivity已在AndroidManifest.xml中注册,否则会跳转失败:<activity android:name=".Website" /> LONG_PRESS_TRIGGER_TIME可根据需求修改数值,单位为毫秒- 返回
true表示消费触摸事件,避免后续触发系统默认的点击/长按逻辑
内容的提问来源于stack exchange,提问作者Xtra 514
相关产品推荐
相关产品推荐

