How to get the click position of ClickSpan in Android TextView

// 计算点击的单词的坐标,首先计算单词在整个短文中的起始位置,即可获取到该单词的x偏移。通过起始位置
    // 还可以获取该单词所在的行索引。进而可以获取该行所在的矩形区域。即可获取到该单词的y偏移。在计算
    // padding和scroll的影响,最终可以获得点击位置的屏幕坐标
    private void calcClickPosition(View widget, int[] pos, ClickableSpan clickableSpan) {
        TextView textView = (TextView) widget;
        Rect parentTextViewRect = new Rect();

        Spanned spannedString = (Spanned) textView.getText();
        // 获取点击单词的起始索引
        int start = spannedString.getSpanStart(clickableSpan);
        Layout textViewLayout = textView.getLayout();
        // 获取点击单词所在的行数
        int lineOffset = textViewLayout.getLineForOffset(start);
        // 获取点击单词所在的x坐标
        double clickX = textViewLayout.getPrimaryHorizontal(start);
        // 获取点击单词所在一行的矩形
        textViewLayout.getLineBounds(lineOffset, parentTextViewRect);
        int[] parentTextViewLocation = {0, 0};
        // 获取TextView左上角的坐标
        textView.getLocationOnScreen(parentTextViewLocation);
        // 加入scroll和padding的偏移的计算
        parentTextViewRect.bottom += parentTextViewLocation[1] + textView.getCompoundPaddingTop()- textView.getScrollY();

        parentTextViewRect.left += parentTextViewLocation[0] + clickX + textView.getCompoundPaddingLeft() - textView.getScrollX();
        pos[0] = parentTextViewRect.left;

        int lineHeight = 20;
        pos[1] = (int) (parentTextViewRect.bottom - textView.getLineSpacingExtra() - textView.getLineSpacingMultiplier() * lineHeight);
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325056726&siteId=291194637
Recommended