SimpleProgrammer
SimpleProgrammer

Reputation: 3

Changing what the enter button does while stopping it from doing it's automatic action

When I press the enter button with focus on an EditText on my Android app, it switches the focus to the next EditText. I added functionality to the enter button in the java class, but cant find out how to disable this focus switch (which is the natural function of the enter key) well. I am using the xml android:inputType="numberDecimal" type of keyboard.

Here's how I am adding functionality to the enter button in Java:

mMyEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {

                    //This code occurs when enter is clicked on the keyboard on this EditText.
                    //press button:
                    mMyButton.performClick();

                    
                    return true;
                }
                return false;
            }
        });

This works to add functionality to the enter button! But when I press the enter button, it still skips to the next EditText.

My question is building on this other question: Android: catching action for keyboard enter button being pressed

At that question, Xaver Kapeller mentioned: "

You can specify which action is performed by ENTER by specifiying android:imeOptions in XML.

I tried this by adding the following line of code to my EditText in xml:

android:imeOptions="actionDone"

This was the only imeOptions selection that partially worked. It: -Disables the enter button from skipping to the next EditText. -Makes the code above not work, that gets the enter action above. -Makes the keyboard go away when enter is pressed.

android:imeOptions="actionNone" seems like it should work, but it still skips to the next EditText.

I'd love an option that keeps the keyboard raised, and allows me to do the other things too.

Upvotes: 0

Views: 37

Answers (1)

Sufiyan Haldar
Sufiyan Haldar

Reputation: 51

You can use the setOnEditorActionListener method instead of setOnKeyListener to handle the Enter key press. This method is specifically designed to handle actions on the soft keyboard.

mMyEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            // This code occurs when enter is clicked on the keyboard on this EditText.
            // press button:
            mMyButton.performClick();
            return true;
        }
        return false;
    }
});

In your XML, you can keep android:imeOptions="actionDone" to prevent the focus from moving to the next EditText.

Upvotes: 0

Related Questions