android-cn / android-discuss

Android 问题交流讨论坛, 微信公众号:codekk, 网站:
https://github.com/android-cn/android-discuss/issues
Apache License 2.0
4.08k stars 537 forks source link

TextView 当设置了setMovementMethod方法后 在设置Ellipsize=end属性时 省略号不展示 #725

Open Apollo2011 opened 6 years ago

Apollo2011 commented 6 years ago

TextView 当设置了setMovementMethod方法后 在设置Ellipsize=end属性时 省略号不展示

demoNo commented 6 years ago
public class TextViewTouchListener implements View.OnTouchListener {
    Spannable spannable;

    public TextViewTouchListener(Spannable spannable) {
        this.spannable = spannable;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (!(v instanceof TextView)) {
            return false;
        }
        TextView textView = (TextView) v;
        if (action == MotionEvent.ACTION_UP ||
                action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= textView.getTotalPaddingLeft();
            y -= textView.getTotalPaddingTop();

            x += textView.getScrollX();
            y += textView.getScrollY();

            Layout layout = textView.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = spannable.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    link[0].onClick(textView);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(spannable,
                            spannable.getSpanStart(link[0]),
                            spannable.getSpanEnd(link[0]));
                }

                return true;
            } else {
                Selection.removeSelection(spannable);
            }
        }

        return false;
    }
}

然后设置TextView,去掉setMovementMethod

textView.setText(str);
textView.setOnTouchListener(new TextViewTouchListener(str));