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)?即可獲取當前字符。