2014-10-09 50 views
-2

我需要從textbox中獲取輸入的單詞以供進一步使用。在Android中的字符串變量中獲取最後輸入的單詞

所以我使用TextWatcheronTextChanged事件我得到edittext框內容。它給出了文本框的全部內容。

但我需要輸入的單詞而不是textbox的全部內容。 一旦用戶按下spacebar,我需要在字符串變量中輸入最後一個單詞。

我的代碼在這裏,temptype持有完整的內容。

tt = new TextWatcher() { 
      public void afterTextChanged(Editable s){ 
       et.setSelection(s.length()); 
      } 
      public void beforeTextChanged(CharSequence s,int start,int count, int after){} 

      public void onTextChanged(CharSequence s, int start, int before, int count) { 
       et.removeTextChangedListener(tt); 
       typed = typed + et.getText().toString(); 
       String temptype; 
       temptype = et.getText().toString(); 
       if (temptype == " "){ 
        showToast("Word: "+typed); 
       } 
       et.addTextChangedListener(tt); 
      } 
     }; 
     et.addTextChangedListener(tt); 
+5

添加您的代碼在這裏...你可以得到最後一個記號形成串,使用子串的方法。 – 2014-10-09 07:04:47

+1

拆分字符串並獲取最後一個數組對象 – 2014-10-09 07:05:26

+1

@Top Cat如果我在句子中間編輯文本,該怎麼辦? – 2014-10-09 07:06:36

回答

1
int selectionEnd = et.getSelectionEnd(); 
String text = et.getText().toString(); 
if (selectionEnd >= 0) { 
    // gives you the substring from start to the current cursor 
    // position 
    text = text.substring(0, selectionEnd); 
} 
String delimiter = " "; 
int lastDelimiterPosition = text.lastIndexOf(delimiter); 
String lastWord = lastDelimiterPosition == -1 ? text : 
    text.substring(lastDelimiterPosition + delimiter.length()); 
// do whatever you need with the lastWord variable 
相關問題