【问题标题】:Getting last typed word in a string variable in Android在Android中的字符串变量中获取最后输入的单词
【发布时间】:2014-10-09 07:03:01
【问题描述】:

我需要从textbox 获取输入的单词以供进一步使用。

所以我使用TextWatcher 并在onTextChanged 事件中获得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);

【问题讨论】:

  • 在此处添加您的代码...您可以使用子字符串方法从该字符串中获取最后一个令牌。
  • 拆分字符串并获取最后一个数组对象
  • @Top Cat 如果我在句子中间编辑文本怎么办?
  • 我的应用是一个音译应用,我需要将输入的单词发送到服务器进行音译。从服务器接收到音译文本后,我想用这个音译词替换输入的单词。
  • 重点仍然是,如果你得到了整个字符串,你显然已经输入了最后一个;你只需要得到它。

标签: java android textwatcher


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2020-02-14
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多