TextView 跟 ClickableSpan 点击事件冲突(文本中有@功能)

需要我们自定义一个父类 重写OnTouch 解决事件冲突 
public class CustomLinkMovementMethod extends LinkMovementMethod {

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        boolean b = super.onTouchEvent(widget,buffer,event);
        //解决点击事件冲突问题
        if(!b && event.getAction() == MotionEvent.ACTION_UP){
            ViewParent parent = widget.getParent();//处理widget的父控件点击事件
            if (parent instanceof ViewGroup) {
                return ((ViewGroup) parent).performClick();
            }
        }
        return b;
    }

    public static CustomLinkMovementMethod getInstance() {
        if (sInstance == null)
            sInstance = new CustomLinkMovementMethod();

        return sInstance;
    }


    private static CustomLinkMovementMethod sInstance;

}

下面写了两点 来解决点击冲突:

1.textView.setMovementMethod(CustomLinkMovementMethod.getInstance());

2. 重写ClickableSpan类   在其onClick事件中 再设置setMovementMethod

public class ClickAtUserSpan extends ClickableSpan {

    private Context context;
    private UserModel userModel;
    private SpanAtUserCallBack spanClickCallBack;
    private int color;

    public ClickAtUserSpan(Context context, UserModel userModel, int color, SpanAtUserCallBack spanClickCallBack) {
        this.context = context;
        this.userModel = userModel;
        this.spanClickCallBack = spanClickCallBack;
        this.color = color;
    }

    @Override
    public void onClick(View view) {
        if (spanClickCallBack != null) {
            ((TextView) view).setMovementMethod(CustomLinkMovementMethod.getInstance());
            spanClickCallBack.onClick(view, userModel);
        }
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        /** 给文字染色 **/
        ds.setColor(color);
        /** 去掉下划线 , 默认自带下划线 **/
        ds.setUnderlineText(false);
    }

}

你可能感兴趣的:(TextView 跟 ClickableSpan 点击事件冲突(文本中有@功能))