美文网首页
设置LinkMovementMethod时禁止Textview滚

设置LinkMovementMethod时禁止Textview滚

作者: 乔伊苏 | 来源:发表于2017-07-14 14:29 被阅读287次

在listview里给TextView设置多ImageSpan时,设置了

 textView.setMovementMethod(LinkMovementMethod.getInstance());

这可能导致TextView可被滑动,而且在设置ImageSpan时,为了让textview里的图片可点击,同时设置了ClickableSpan
,此时可能会出现点击的图片和回调的图片不一致。
解决图片不一致的方法如下:
新建一个类


public class LinkMovementMethodOverride implements View.OnTouchListener{

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        TextView widget = (TextView) v;
        Object text = widget.getText();
        if (text instanceof Spanned) {
            Spanned buffer = (Spanned) text;

            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);
                /**
                 * 下面这几行就是解决图片点击错位的
                 */
                float xLeft=layout.getPrimaryHorizontal(off);
                if(xLeft<x){
                    off+=1;
                }else{
                    off-=1;
                }

                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 only works on Spannable text. In our case setSelection doesn't work on spanned text
                        //Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                    }
                    return true;
                }
            }

        }

        return false;
    }

}

最后

 //  textView.setMovementMethod(LinkMovementMethod.getInstance());
     textView.setOnTouchListener(new LinkMovementMethodOverride());

问题解决

相关文章

网友评论

      本文标题:设置LinkMovementMethod时禁止Textview滚

      本文链接:https://www.haomeiwen.com/subject/bbonhxtx.html