6

I am using touch listener on text view. I can get the touch coordinates through motion event.

Can I get the character index or near by character coordinates on which I clicked.

Eg., Hello Android

This is my text. Now I can get the x y coordinates but can I get the character index, say A, when I touch it.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
android developer
  • 1,253
  • 2
  • 13
  • 43

1 Answers1

13

You have to overide onTouch()

Try with the following

public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
         Layout layout = ((TextView) v).getLayout();
            int x = (int)event.getX();
            int y = (int)event.getY();
            if (layout!=null){
                int line = layout.getLineForVertical(y);
                int characterOffset = layout.getOffsetForHorizontal(line, x);
                Log.i("index", ""+characterOffset);
                }
            return true;


    }
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243