Search code examples
javaandroidtextwatcher

Getting last typed word in a string variable in Android


I need to get the typed words from textbox for further use.

So i am using the TextWatcher and at onTextChanged event i am getting the edittext box Content. It gives the full content of the text box.

But i need the typed word not the full content of the textbox. I need the last typed word in a string variable once the user press the spacebar.

My code is here and temptype holding the full content.

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);

Solution

  • 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