0
我想要在觸摸時在我的應用程序中使用Ontouch座標的幫助來獲取字符的位置。這應該怎麼做。 請幫我 在此先感謝如何在editext中獲取onTouch中的字符位置
我想要在觸摸時在我的應用程序中使用Ontouch座標的幫助來獲取字符的位置。這應該怎麼做。 請幫我 在此先感謝如何在editext中獲取onTouch中的字符位置
我已經寫了一個方法來做到這一點。它適用於TextView,但應該適用於EditText,因爲它擴展了TextView。製作一個自定義的EditText並在此處粘貼此方法。
注 x和y是所述的getX()和的getY()的MotionEvent的部件OnTouch
期間public int getCharIndexFromCoordinate(int x, int y) {
// Offset the top padding
int height = getPaddingTop();
for (int i = 0; i < getLayout().getLineCount(); i++) {
Rect bounds = new Rect();
getLayout().getLineBounds(i, bounds);
height += bounds.height();
if (height >= y) {
int lineStart = getLayout().getLineStart(i);
int lineEnd = getLayout().getLineEnd(i);
Spanned span = (Spanned) getText();
RelativeSizeSpan[] sizeSpans = span.getSpans(lineStart, lineEnd, RelativeSizeSpan.class);
float scaleFactor = 1;
if (sizeSpans != null) {
for (int j = 0; j < sizeSpans.length; j++) {
scaleFactor = sizeSpans[j].getSizeChange();
}
}
String lineSpan = getText().subSequence(lineStart, lineEnd).toString();
float[] widths = new float[lineSpan.length()];
TextPaint paint = getPaint();
paint.getTextWidths(lineSpan, widths);
float width = 0;
for (int j = 0; j < lineSpan.length(); j++) {
width += widths[j] * scaleFactor;
if (width >= x || j == lineSpan.length() - 1) {
return lineStart + j;
}
}
}
}
return -1;
}