Android TextView获取ClickSpan点击位置的方法

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>> hot3.png

// 计算点击的单词的坐标,首先计算单词在整个短文中的起始位置,即可获取到该单词的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);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值