您的位置:首页 > 移动开发 > Android开发

在TextView中使用了ClickableSpan后,禁止TextView滑动。

2017-12-11 11:13 288 查看
  最近在项目中做一个文字展开/收起的功能,TextView默认显示2行,点击旁边的展开按钮显示全部内容。我这里的收起功能使用TextView的setMaxLine方法。然而我的TextView中有用到ClickableSpan,这就导致在TextView的内容收起时,如果点击TextView,文本内容就会擅自滑动,让人很是郁闷。究其原因,是因为我为TextView设置的LinkMovementMethod的touch事件在捣鬼:这货继承的是ScrollingMovementMethod,当调用onTouchEvent方法的时候会让控件内容可以滑动,所以我们可以用下边自定义的继承自BaseMovementMethod的类来取代LinkMovementMethod:

/**
* 替换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时内容也不会乱动了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息