LinkMovementMethod返回长按以及点击事件给父类处理

1、实现方式:

当textview设置LinkMovementMethod后会拦截掉父类的 点击事件和长按事件,此时我们需要重写LinkMovementMethod的onTouchEvent(TextView widget, Spannable buffer, MotionEvent event);方法对span以及点击非span的长按、点击事件处理,当点击span区域时,textview的onTouchEvent(MotionEvent event);返回true,其他情况下返回false交给父布局处理即可。

2、实现自定义LinkMovementMethod:

重写自定义LinkMovementMethod的onTouchEvent(TextView widget, Spannable buffer, MotionEvent event)代码如下:

    @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);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(link[0]),
                            buffer.getSpanEnd(link[0]));
                }
                // tiantian add to modify link hit flag
                //statusTextview是我们需要使用的自定义的textview,里面写一个标志位                
                //mLinkHitFlag为true代表span点击,所以点击span设置。
                //statusTextview你的自定义textview类名(自己起)
                if(widget instanceof StatusTextView){
                    ((StatusTextView)widget).mLinkHitFlag=true;
                }
                return true;
            } else {
                Selection.removeSelection(buffer);
            }
        }
        return super.onTouchEvent(widget, buffer, event);
    }

    public static LinkMovementClickMethod getInstance() {
        if (null == sInstance) {
            sInstance = new LinkMovementClickMethod();
        }
        return sInstance;
    }

    private static LinkMovementClickMethod sInstance;

}

3、重写自定义textview的onTouchEvent(MotionEvent event)方法:

   
    public  boolean mLinkHitFlag = false;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mLinkHitFlag=false;
        super.onTouchEvent(event);//textview会调用设置的LinkMovementMethod的onTouchevent
        return  mLinkHitFlag;
    }

 

你可能感兴趣的:(android)