Android单击、长按获取当前触点坐标下(TextView)文字字符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/admans/article/details/85244250
package com.*.*.*.utils;

import android.graphics.Rect;
import android.text.Layout;
import android.widget.TextView;

public class TextViewUtils
{
    /**
     获取TextView某一个字符的坐标位置
     @return 返回的是相对坐标
     @parms tv
     @parms index 字符索引
     */
    public static Rect getTextViewSelectionRect(TextView tv, int index) {
        Layout layout = tv.getLayout();
        Rect bound = new Rect();
        int line = layout.getLineForOffset(index);
        layout.getLineBounds(line, bound);
        int yAxisBottom = bound.bottom;//字符底部y坐标
        int yAxisTop = bound.top;//字符顶部y坐标
        int xAxisLeft = (int) layout.getPrimaryHorizontal(index);//字符左边x坐标
        int xAxisRight = (int) layout.getSecondaryHorizontal(index);//字符右边x坐标
        //xAxisRight 位置获取后发现与字符左边x坐标相等,如知道原因请告之。暂时加上字符宽度应对。
        if (xAxisLeft == xAxisRight)
        {
            String s = tv.getText().toString().substring(index, index + 1);//当前字符
            xAxisRight = xAxisRight + (int) tv.getPaint().measureText(s);//加上字符宽度
        }
        int tvTop=tv.getScrollY();//tv绝对位置
        return new Rect(xAxisLeft, yAxisTop+ tvTop, xAxisRight, yAxisBottom+tvTop );
        
    }
    
    /**获取TextView触点坐标下的字符
     @param tv tv
     @param x 触点x坐标
     @param y 触点y坐标
     
     @return 当前字符
     */
    public static String getTextViewSelectionByTouch(TextView tv, int x, int y) {
        String s = "";
        for (int i = 0; i < tv.getText().length(); i++)
        {
            Rect rect = getTextViewSelectionRect(tv, i);
            if (x < rect.right && x > rect.left && y < rect.bottom && y > rect.top)
            {
                s = tv.getText().toString().substring(i, i + 1);//当前字符
                break;
            }
        }
        return s;
    }
}

在 点击事件中通过获取触点坐标后调用 TextViewUtils.getTextViewSelectionByTouch(tv, x, y) 即可获取当前字符。

猜你喜欢

转载自blog.csdn.net/admans/article/details/85244250