2011-07-06 28 views

回答

2

我已經寫了一個方法來做到這一點。它適用於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; 
} 
相關問題