Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing AutoFill on EditText

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.

like image 528
JuiCe Avatar asked Apr 17 '26 21:04

JuiCe


1 Answers

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

like image 50
StarsSky Avatar answered Apr 22 '26 02:04

StarsSky