详谈Android中onTouch与onClick事件的关系(必看)

详谈Android中onTouch与onClick事件的关系(必看),第1张

概述这几天遇到点关于Android的触摸事件相关的,还跟onClick有关,暂且记下:LinearLayout分别设置了onTouchListener,onClickListener,onLongClickListener及onTouchEvent回调

这几天遇到点关于AndroID的触摸事件相关的,还跟onClick有关,暂且记下:

linearLayout分别设置了ontouchListener,onClickListener,onLongClickListener及ontouchEvent回调

1、在屏幕上触摸之后基本的执行流程如下:

ontouch,action=0ontouchEvent,action=0ontouch,action=2ontouchEvent,action=2ontouch,action=1ontouchEvent,action=1onClick

也就是先说ontouchListener是最先被触发的,然后是本身的ontouchEvent回调;当最后的up事件发生并被ontouchEvent处理后才会触发onClickListener。

2、把ontouchEvent回调中的super.ontouchEvent去除,直接返回true;则流程如下:

ontouch,action=1

可以看到onClickListener永远无法被触发,也侧面说明了对onClick的触发是在ontouchEvent回调中来实现的。

3、长按屏幕,流程如下:

ontouch,action=2onLongClickontouch,action=1onClick

当长按的时候,无需到up就会触发onLongClick的响应,但之后也会继续触发onClick的响应。

4、但如果在onLongClick中返回true,则流程如下,即只在中间触发了onLongClick,之后会继续响应touch,但当up的时候就不会再触发onClick

ontouch,action=0ontouchEvent,action=1

测试代码如下:

public class MainActivity extends Activity {  @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    FrameLayout frame = (FrameLayout)findVIEwByID(R.ID.container);    linearLayoutTest line = new linearLayoutTest(this);    line.setonClickListener(new ClickListener());    line.setonLongClickListener(new LongClickListener());    line.setontouchListener(new touchListener());    line.setLongClickable(true);    frame.addVIEw(line);  }  public class ClickListener implements OnClickListener {    @OverrIDe    public voID onClick(VIEw v) {      Log.e("test","onClick");    }  }  public class LongClickListener implements OnLongClickListener{    @OverrIDe    public boolean onLongClick(VIEw v) {      Log.e("test","onLongClick");      return true;    }  }  public class touchListener implements OntouchListener{    @OverrIDe    public boolean ontouch(VIEw v,MotionEvent event) {      Log.e("test","ontouch,action="+event.getAction());      return false;    }   }    }public class linearLayoutTest extends linearLayout{  public linearLayoutTest(Context context) {    super(context);  }  @OverrIDe  public boolean ontouchEvent(MotionEvent event) {    Log.e("test","ontouchEvent,action="+event.getAction());    return super.ontouchEvent(event);  }}

以上这篇详谈AndroID中ontouch与onClick事件的关系(必看)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的详谈Android中onTouch与onClick事件的关系(必看)全部内容,希望文章能够帮你解决详谈Android中onTouch与onClick事件的关系(必看)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1146543.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存