3

I have an EditText field which I would like to introduce some sort of Auto-Fill feature on. All I am currently trying to do is fill the the EditText box with "Special CT" if the "S" button is pressed. This is what I have:

ctEditText = (EditText) findViewById( 1001 );
    ctEditText.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i( "KEY", "PRESSED" );
            // if keydown and "enter" is pressed
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {

                return true;

            } else if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_S)) {
                Log.i( "KEY", "S" );
                if( ctEditText.getText().toString().length() == 1 ) {
                    ctEditText.setText( "Special CT" );
                }
                return true;
            }

            return false;
        }
     });

With this code, pressing the "S" button does absolutely nothing for me. My LogCat does not show either of my LogCalls until I press the enter button in the bottom right of the keyboard. And when I press the enter button, it displays the KEY PRESSED log call twice, no matter how many different keys I have pressed prior to the enter button.

EDIT

So after messing around with it some more I have realized that the reason the Log call appears twice is because it is appearing when I release the enter key as well. I also got the S key to call the KEY PRESSED log call but it is still not recognized in my If statement.

JuiCe
  • 4,132
  • 16
  • 68
  • 119

1 Answers1

1

Try this:

ctEditText = (EditText) findViewById( 1001 );
ctEditText.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Log.i( "KEY", "PRESSED" );
        // if keydown and "enter" is pressed
        if (ctEditText.getText().toString().equalsIgnoreCase("S")) {
            Log.i( "KEY", "S" );               
            ctEditText.setText( "Special CT" );               
            return true;
        }
        else if ((event.getAction() == KeyEvent.ACTION_DOWN)
            && (keyCode == KeyEvent.KEYCODE_ENTER)) {

            return true;

        } 

        return false;
    }
 });

just check that the Text entered is equal to "S"

if (ctEditText.getText().toString().equalsIgnoreCase("S"))

Even better, you can use TextWatcher example

Community
  • 1
  • 1
StarsSky
  • 6,721
  • 6
  • 38
  • 63
  • I tried using the first code block, but unfortunately pressing the "S" key doesn't trigger the `OnKeyListener` at all, so the if statement never even has a chance of being reached. As for the `TextWatcher`, I don't think thats the best for my situation. I have a lot of EditText fields to manipulate but only a few would benefit more with the TextWatcher, I want to keep it uniform. – JuiCe Feb 06 '13 at 14:35