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) 即可获取当前字符。