2014-10-09 119 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 
相关问题