在TextView中使用了ClickableSpan后,禁止TextView滑动。
2017-12-11 11:13
288 查看
最近在项目中做一个文字展开/收起的功能,TextView默认显示2行,点击旁边的展开按钮显示全部内容。我这里的收起功能使用TextView的setMaxLine方法。然而我的TextView中有用到ClickableSpan,这就导致在TextView的内容收起时,如果点击TextView,文本内容就会擅自滑动,让人很是郁闷。究其原因,是因为我为TextView设置的LinkMovementMethod的touch事件在捣鬼:这货继承的是ScrollingMovementMethod,当调用onTouchEvent方法的时候会让控件内容可以滑动,所以我们可以用下边自定义的继承自BaseMovementMethod的类来取代LinkMovementMethod:
在为TextView设置MovementMethod时使用这个自定义的MovementMethod
/** * 替换LinkMovementMethod,这个不会触发TextView的滑动事件 * 单例模式——饿汉 */ public static class CustomMovementMethod extends BaseMovementMethod { private static CustomMovementMethod customMovementMethod; public static CustomMovementMethod getInstance() { if (customMovementMethod == null) { synchronized (CustomMovementMethod .class) { if (customMovementMethod == null) { customMovementMethod = new CustomMovementMethod (); } } } return customMovementMethod; } @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { //除了点击事件,我们不要其他东西 link[0].onClick(widget); } return true; } } return true; } private CustomMovementMethod () { } }
在为TextView设置MovementMethod时使用这个自定义的MovementMethod
commentTextView.setMovementMethod(CustomMovementMethod.getInstance());这样即使设置了ClickSpan,在我们为TextView设置了最大行数后,触摸TextView时内容也不会乱动了。
相关文章推荐
- 聊天记录,踩的坑:设置EditText焦点;EditText软键盘和recyclerview的交互;SpannableStringBuilder的使用;ClickableSpan失效;软键盘挡住edi
- TextView中ClickableSpan与文本自由复制(TextIsSelectable)冲突问题
- Android事件系统(2)ClickableSpan In Clickable TextView
- Android textView文字添加图片 imageSpan使用
- 浅谈ClickableSpan , 实现TextView文本某一部分文字的点击响应
- android TextView ClickableSpan 长按报错
- Android开发之Viewpager与TextView结合使用时不能滑动的问题
- Android TextView ClickableSpan 分段点击实现
- Android使用ViewPager实现导航页根据情况禁止滑动以及点击切换
- TextView中使用ImageSpan显示“...”问题
- ListView的Item里的TextView设置ClickableSpan和LinkMovementMethod导致ListView无法响应点击事件
- Android之TextView的样式类Span的使用详解
- TextView ClickableSpan 事件分发的两个坑
- Android学习—— TextView ClickableSpan 点击链接事件 改超链接颜色
- Android TextView Span的使用详解
- textView设置ClickableSpan点击空白位置也响应点击
- android-----使用ImageSpan对象在TextView组件中显示图像
- android ListView使用ViewHolder优化时,EditText设置TextWatcher时,滑动ListView导致内容错乱
- Android中Recyclerview使用15----禁止RecycleView的滑动
- TextView ClickableSpan onClickListener点击事件冲突