开发者

How to get the position of character at onTouch in editext

i want to get the Position of the character at the time of touch on the editext box in开发者_如何学运维 my application with the help of the coordinates of Ontouch. How should this be possible . Please help me Thanks in advance


I've written a method to do just that. It's for TextView, but should work for EditText since it extends TextView. Make a custom EditText and stick this method in there.

NOTE x and y are the getX() and getY() component of the MotionEvent during 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜