2016-11-03 28 views
0

現在我想解釋清楚,現在在Activity中,我有一個長字符串,例如一個字符串,它有50個單詞。如何在textview中點擊特定單詞時從字符串中提取單詞Android

當我點擊一個詞我只想得到那個詞。 例如:如果我點擊蘋果,該字應該得到或應該打印在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; 
    } 
}); 

我試過了,我只能得到偏移點,但不知道如何得到整個單詞。

由於提前

+0

http://stackoverflow.com/questions/ 11601139 /如果你有偏移量,那麼在這個字符串的偏移量之前和之後找到下一個空間,這就是你如何得到整個單詞的方式。 –

+0

我試過這個,但這不是爲我工作,,, onclick方法不叫永遠 –

回答

0

如果你的目標API級別14+,您可以使用getOffsetForPosition()。

對於以前的Android版本,請查看您是否可以從Android源代碼複製此方法的代碼並擴展您自己的TextView。

+0

感謝您的回覆...但我已經得到了X和Y的職位,但我想得到確切的單詞不職位,請幫助我 –

0

您可以使用getOffsetForPosition()

+0

謝謝你的回覆,我希望那個單詞點擊..不偏移位置 –

1

我希望它會幫助你找到的onclick詞,因爲你在問題中提到您已經找到了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); 

    } 
+0

謝謝莎哈布。它真的我想..它對我感謝的幫助 –

相關問題