Android单击、长按获取当前触点坐标下(TextView)文字字符
生活随笔
收集整理的這篇文章主要介紹了
Android单击、长按获取当前触点坐标下(TextView)文字字符
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package com.*.*.*.utils;import android.graphics.Rect;
import android.text.Layout;
import android.widget.TextView;public class TextViewUtils
{/**獲取TextView某一個(gè)字符的坐標(biāo)位置@return 返回的是相對(duì)坐標(biāo)@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坐標(biāo)int yAxisTop = bound.top;//字符頂部y坐標(biāo)int xAxisLeft = (int) layout.getPrimaryHorizontal(index);//字符左邊x坐標(biāo)int xAxisRight = (int) layout.getSecondaryHorizontal(index);//字符右邊x坐標(biāo)//xAxisRight 位置獲取后發(fā)現(xiàn)與字符左邊x坐標(biāo)相等,如知道原因請(qǐng)告之。暫時(shí)加上字符寬度應(yīng)對(duì)。if (xAxisLeft == xAxisRight){String s = tv.getText().toString().substring(index, index + 1);//當(dāng)前字符xAxisRight = xAxisRight + (int) tv.getPaint().measureText(s);//加上字符寬度}int tvTop=tv.getScrollY();//tv絕對(duì)位置return new Rect(xAxisLeft, yAxisTop+ tvTop, xAxisRight, yAxisBottom+tvTop );}/**獲取TextView觸點(diǎn)坐標(biāo)下的字符@param tv tv@param x 觸點(diǎn)x坐標(biāo)@param y 觸點(diǎn)y坐標(biāo)@return 當(dāng)前字符*/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);//當(dāng)前字符break;}}return s;}
}
在?點(diǎn)擊事件中通過獲取觸點(diǎn)坐標(biāo)后調(diào)用 TextViewUtils.getTextViewSelectionByTouch(tv, x, y)?即可獲取當(dāng)前字符。
總結(jié)
以上是生活随笔為你收集整理的Android单击、长按获取当前触点坐标下(TextView)文字字符的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “*** IS NOT TRANSLAT
- 下一篇: Android TextView设置Cl