1

Now I want to explain clearly, now in an Activity I have a long string for example a string which have 50 words.

When I click on a word I want to get that word only. For ex : If I click on Apple, that word should get or should print in Log.

text1.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Layout layout = ((TextView) v).getLayout();
        int x = (int) event.getX();
        int y = (int) event.getY();
        if (layout != null) {
            int line = layout.getLineForVertical(y);
            int offset = layout.getOffsetForHorizontal(line, x);
            Log.v("index", "" + offset + " Line :" + line);
        }
        return true;
    }
});

I tried it and I can get offset points only but don't know how to get a whole word.

Thanks in Advance

vidulaJ
  • 1,232
  • 1
  • 16
  • 31
Villonava Anand
  • 65
  • 1
  • 10
  • http://stackoverflow.com/questions/11601139/determining-which-word-is-clicked-in-an-android-textview if you have offset then find the next space after and before this offset in string that's how you can get the whole word. – Shahab Rauf Nov 03 '16 at 06:56
  • i tried this but this is not working for me,,, onclick method is not called ever – Villonava Anand Nov 03 '16 at 07:13

3 Answers3

1

I Hope it will help you to find the onclick word, as you mentioned in question you have found the offsetposition

public static String getWord(String textOfTextView, int offsetPosition)
    {
        int endpositionofword = 0;
        int startpositionofword = 0;
       for (int i = offsetPosition; i<textOfTextView.length();i++)
       {
           if (i==textOfTextView.length()-1) {
               endpositionofword = i;
               break;
           }
           if (textOfTextView.charAt(i)==' ') {
               endpositionofword = i;
               break;
           }

       }
        for (int i = offsetPosition; i>=0;i--)
        {
            if (i==0) {
                startpositionofword = i;
                break;
            }
            if (textOfTextView.charAt(i)==' ') {
                startpositionofword = i;
                break;
            }

        }
        return textOfTextView.substring(startpositionofword,endpositionofword);

    }
Shahab Rauf
  • 3,651
  • 29
  • 38
0

If you're targeting API level 14+, you could use getOffsetForPosition().

For previous Android version, see if you can copy the code for this method from Android source and extend your own TextView.

LoveAndroid
  • 186
  • 1
  • 11
0

You can use getOffsetForPosition()

Vishnu Prasad
  • 584
  • 4
  • 11