Skip to content Skip to sidebar Skip to footer

Making Sure Edittext Only Returns Single Lowercase Letters

I'm porting my old Hangman java game to android for my programming finals in january. I've gotten most of it working but i have found that my does not do any checks for invalid cha

Solution 1:

Solution 2:

You would want to first set a KeyListener using the setKeyListener method of the TextView. You would then override the onKeyDown method of the KeyListener you set and listen for input. If what is typed is NOT a character (ie: A - Z) then you would throw out the input and cancel the event. If what was typed was a character you should convert the character to lowercase before adding it to the text box.

Edit -

Just noticed you're not doing this on key presses but instead the user has to hit "Ok". This makes your life easier.

When the user presses "Ok" check to see if the text is a valid character (ie: Only one character and is between A - Z). If it's not, yell at the user. If it is, either check to see if it's lowercase or conver it to lowercase yourself.

http://developer.android.com/reference/android/widget/TextView.html#setKeyListener(android.text.method.KeyListener)

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Character.html#toLowerCase(char)

Solution 3:

I found that for this particular problem the easiest solution would be an array filled with only the valid characters. So instead of blacklisting non-valid characters and symbols i simply whitelist the relatively few that are valid.

Here is the array if anyone needs it in the future:

finalString[] allowedChars = {"a", "b", "c", "d", "e", 
                "f", "g", "h", "i", "j", 
                "k", "l", "m", "n", "o", 
                "p", "q", "r", "s", "t", 
                "u", "v", "w", "x", "y", 
                "z"};

Using a loop for comparing:

for(int n = 0; n < allowedChars.length; n++){
        if(allowedChars[n].equalsIgnoreCase(guess)){
        //Game logic here
        }}

Post a Comment for "Making Sure Edittext Only Returns Single Lowercase Letters"