How do I use TextWatcher to check for a specific string of characters instead of just one character?

StackOverflow https://stackoverflow.com/questions/10058524

Domanda

I'm new to both Android and Java. My app needs to be able to check what the user is typing as they are typing it. If the user types in a predetermined word that has been flagged, an event needs to occur before the user presses a button. It seems like the best choice for this would be a TextWatcher and an addChangedTextListener. I haven't been able to figure out how to get it to check a sequence of characters (a word). For instance, if the flagged word was "very", when the user types "It is very warm." in the edittext, the program should be able to recognize that "very" was typed and alert the user in some way.

I hope I was able to make this clear without using any code. Any help that could be given would be greatly appreciated.

È stato utile?

Soluzione

This is the simplest form of doing it via TextWatcher:

String word = "very";

TextWatcher watcher = new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void afterTextChanged(Editable s) {
        String tmp = s.toString().trim().toLowerCase();
        if(tmp.contains(word.toLowerCase())){
            //inform the user here
        }
    }
};

Altri suggerimenti

I will simply show an example:

String word = "very";
int wordProgress = 0;

charTyped(char c) {
    if (c == word.charAt(wordProgress)) {
        wordProgress++;
        if (wordProgress >= word.length()) {
            AlertUserThatFlagWordWasTypedAndUseObjectiveCTypeMethodNamingSyntaxJustForFunBecauseIAmUsingObjectiveCAndIFindItQuiteAnoying(word);
        }
    }
}

This may not be the best way to do it, but it is the fastest and most efficient. If you are also looking for caret position changes and backspaces, then you will have to modify this.

A much simpler version that would also work with backspaces and caret movements, but would be much less efficient, would be to check if the entire text area contained the word every time the user typed something.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top